我正在尝试在IOS上实现网址下载的排队机制。为此,我使用 NSURLConnection用于网络访问部分,我将它们排入NSOperationQueue类的静态实例(在UIControllers之间共享)。下载开始时,我使用NSURLConnectionDownloadDelegate的回调更新UI进度条。 有一个UIController视图,一个UIView。 Queue在ViewLoad中创建,并分配给定义为UIControllerView属性的指针
//UIControllerView Code
- (void)viewDidLoad
{
[super viewDidLoad];
self.myDownloadQueue = [NSOperationQueue sharedOperationQueue];
}
并且实施遵循建议here
通过按钮启动下载,创建一个新的NSURLConnection,并通过SetDelegateQueue将其发送到NSOperationQueue:
- (IBAction)startDownload:(UIButton *)sender {
NSString *url = @"<myURL blablabl>";
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30];
NSURLConnection *urlConn = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
[urlConn setDelegateQueue:self.myDownloadQueue];
[urlConn start];
NSLog(@"adding a new task for url %@",[[urlConn currentRequest] URL ]);
//Sets the UI
self.awProgress1.progress=0;
}
UIViewController为方法
实现NSURLConnectionDataDelegate协议 @interface awViewController : UIViewController <NSURLConnectionDownloadDelegate>
@end
...snip....
@implementation
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
{snip.. updates the progress bar here using performSelectorOnMainThread:@selector()..
}
- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes{...snip...}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL{....snip...}
@end
在IOS6上,代码工作正常,当UIViewController收到[连接didWriteData:]调用时,UI栏会更新。 然而,在IOS5上,当网址完全下载时,用户界面冻结.... 一步一步的调试表明,在这两种情况下,代码都会在下载结束时达到IOS运行时,即它不会卡在我的代码中。 在下载过程中用户界面很好,我可以按下按钮......
如果我将NSURLCOnnection设置为在主线程中运行,即删除
[urlConn setDelegateQueue:self.myDownloadQueue];
[urlConn start];
然后代码再次在IOS5上运行。但这不是我想要的,我希望下载在后台线程中执行。
我错过了什么?是否有一些家务管理在IOS5上排队明智?实际上,当NSURLConnection完成时,问题就出现了,因为在下载期间UI很好。
谢谢你的帮助 !
-A
PS:示例代码可用,只是不想让屏幕太杂乱......