Ios NSURLConnection进度条与sendAsynchronousRequest Objective-C
我用下面的方法下载了大量的zip文件。这可能需要一些时间,所以我想显示一个进度条 我已经研究了如何使用NSURLConnection的委托方法,这看起来很简单,但是我想用“sendAsynchronousRequest”实现同样的功能。如何获得下载时下载的字节数以及预期的总字节数,以便显示进度条?我明白,如果以我正在进行的方式开始下载,我就不能使用委托方法Ios NSURLConnection进度条与sendAsynchronousRequest Objective-C,ios,iphone,objective-c,cocoa,nsurlconnection,Ios,Iphone,Objective C,Cocoa,Nsurlconnection,我用下面的方法下载了大量的zip文件。这可能需要一些时间,所以我想显示一个进度条 我已经研究了如何使用NSURLConnection的委托方法,这看起来很简单,但是我想用“sendAsynchronousRequest”实现同样的功能。如何获得下载时下载的字节数以及预期的总字节数,以便显示进度条?我明白,如果以我正在进行的方式开始下载,我就不能使用委托方法 // Begin the download process - (void)beginDownload:(NSMutableArray *)
// Begin the download process
- (void)beginDownload:(NSMutableArray *)requests {
// Now fire off a bunch of requests asynchrounously to download
self.outstandingRequests = [requests count];
for (NSURLRequest *request in requests) { // Get the request
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// Error check
if ( error != nil ) {
// The alertview for login failed
self.appDelegate.warningView.title = @"Refresh Error!";
self.appDelegate.warningView.message = [error localizedDescription];
// Show the view
[self.appDelegate.warningView show];
// Debug
if ( DEBUG ) {
NSLog(@"A request failed - %d left!",self.outstandingRequests);
}
}
else {
// Debug
if ( DEBUG ) {
NSLog(@"A request is done - %d left!",self.outstandingRequests);
}
}
// Decrement outstanding requests
self.outstandingRequests--;
// No requests are left
if (self.outstandingRequests == 0) {
// Debug
if ( DEBUG ) {
NSLog(@"All requests are done!");
}
// Get rid of loading view
[self performSelector:@selector(dismissLoadingView) withObject:nil afterDelay:0.15];
}
}];
}
}
sendAsynchronousRequest无法满足您的要求,因为在请求完成之前,它不会调用您的回调。您需要使用initRequest:withDelegate:并处理您自己的数据积累 当接收到报头(可能多次用于重定向)时,将调用didReceiveResponse方法,您可以在那里选择预期大小:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_expectedBytes = (NSUInteger)response.expectedContentLength;
_data = [NSMutableData dataWithCapacity:_expectedBytes];
// make a progress update here
}
每次接收到数据块时,您都会收到对委托方法didReceiveData的调用,因此您知道到目前为止您已经接收了多少数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_data appendData:data];
_receivedBytes = _data.length;
// make a progress update here
}
另一种可能是使用AFNetworking这样的框架,它可以为您处理大量的副作用,尽管对于真正简单的使用来说,它可能过于臃肿。