进度条与NSURLConnection

时间:2014-02-28 09:52:59

标签: ios objective-c nsurlconnection

我想在从网址下载视频时显示进度条。我无法弄清楚出错的地方,expectedContentLength总是显示-1。这是代码。

-(void)getResource{
bytesReceived  = 0;
self.progressView.progress = 0.0;
NSString *string = @“MY_URL";
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:string]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
self.feedConnection =  [[NSURLConnection alloc]initWithRequest:request delegate:self]
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
self.responseData = [NSMutableData data];
[self.responseData setLength:0];
float length = [response expectedContentLength];
expectedBytes = [NSNumber numberWithUnsignedInteger:length];
NSLog(@"expected bytes  %f %@",length,expectedBytes);
}

 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseData appendData:data];
float progress = (float)[self.responseData length]/[expectedBytes floatValue];
NSLog(@"%f / %f  is %f", (float)[self.responseData length] ,[expectedBytes floatValue],progress);
self.progressView.progress = progress;
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
   self.feedConnection = nil;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
self.feedConnection = nil;
[self.view setBackgroundColor:[UIColor blackColor]];
[self fetchedData:self.responseData];
self.responseData = nil;
}

1 个答案:

答案 0 :(得分:2)

我认为,您可以使用 NSURLConnectionDownloadDelegate 方法获取totalBytes以及已下载了多少数据。

 - (void)connection:(NSURLConnection *)connection 
       didWriteData:(long long)bytesWritten 
  totalBytesWritten:(long long)totalBytesWritten 
 expectedTotalBytes:(long long) expectedTotalBytes;