下载前计算文件大小

Sag*_*ari 1 iphone xcode download nsurlconnection

我想要做的解释如下.

我有一个MP3文件的网址.(例如声音文件)

当用户启动应用程序时,应该开始下载并为此我实现了以下方法:

-(void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url=[NSURL URLWithString:@"http://xyz.pqr.com/abc.mp3"];
    NSURLRequest *req=[NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:120];

    NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];

    if(con){
        myWebData=[[NSMutableData data] retain];
        } else {
        //          [MainHandler performSelector:@selector(targetSelector:) withObject:nil];
      } 
     }


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    NSLog(@"%@",@"connection established");
    [myWebData setLength: 0];

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"%@",@"connection receiving data");
    [myWebData appendData:data]; 
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"%@",@"connection failed");
    [connection release];
    //  [AlertViewHandler showAlertWithErrorMessage:@"Sorry, there is no network connection. Please check your network and try again."];
//  [self parserDidEndDocument:nil];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
}
Run Code Online (Sandbox Code Playgroud)

以上方法适合下载.但是我无法获得将要下载的确切大小.我想知道文件的大小 - 将要下载.

FKD*_*Dev 7

只需对NSURLResponse传递给以下委托方法的对象使用expectedContentSize :

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

}
-(NSURLRequest *)connection:(NSURLConnection *)connection
        willSendRequest:(NSURLRequest *)request
       redirectResponse:(NSURLResponse *)response {
}
Run Code Online (Sandbox Code Playgroud)

像这样:

long long size = [response expectedContentLength];
Run Code Online (Sandbox Code Playgroud)