Phi*_*Bot 2 iphone cocoa objective-c nsurlconnection ios
我正在使用以下方法下载一堆较大的zip文件.这可能需要一段时间,所以我想显示一个进度条.
我已经研究过如何处理NSURLConnection的委托方法,这似乎很简单,但是我希望用"sendAsynchronousRequest"实现相同的功能.如何获取下载时下载的字节数以及预期的总字节数,以便我可以显示进度条?我知道如果我以我正在进行的方式启动下载,我就无法使用委托方法.
// 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];
}
}];
}
}
Run Code Online (Sandbox Code Playgroud)
如何在下载文件时为NSURLConnection创建进度条?
http://iphonedevsdk.com/forum/iphone-sdk-development/24233-nsurlconnection-with-uiprogressbar.html
http://iphoneeasydevelopment.blogspot.com/2011/10/use-progess-bar-when-downloading-file.html
sendAsynchronousRequest不能用于您的目的,因为它在请求完成之前不会调用您的回调.您需要使用initRequest:withDelegate:并处理您自己的数据累积.
收到标题(可能多次重定向)后,将调用didReceiveResponse方法,您可以在那里获取预期的大小:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_expectedBytes = (NSUInteger)response.expectedContentLength;
_data = [NSMutableData dataWithCapacity:_expectedBytes];
// make a progress update here
}
Run Code Online (Sandbox Code Playgroud)
每次收到一大块数据时,您都会收到委托方法didReceiveData的调用,因此您知道到目前为止您收到了多少数据.
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_data appendData:data];
_receivedBytes = _data.length;
// make a progress update here
}
Run Code Online (Sandbox Code Playgroud)