2

我正在尝试为IOS上的url下载实现排队机制。为此,我将 NSURLConnection 用于网络访问部分,并将它们排入 NSOperationQueue 类的静态实例(在 UIController 之间共享)。下载开始时,我使用来自 NSURLConnectionDownloadDelegate 的回调更新 UI 进度条。有一个UIControllerview,一个UIView。队列在 ViewLoad 中创建,并分配给定义为 UIControllerView 属性的指针

//UIControllerView Code
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        self.myDownloadQueue = [NSOperationQueue sharedOperationQueue];   
    }

并且实施遵循这里的建议

通过一个按钮开始下载,创建一个新的 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 上,代码工作正常,UI 栏会随着 UIViewController 接收到 [connection didWriteData:] 调用而更新。然而,在 IOS5 上,当 url 完全下载时,UI 冻结.... 逐步调试表明,在这两种情况下,下载结束时代码都达到了 IOS 运行时间,即它没有卡在我的代码中的某个地方。下载过程中用户界面很好,我可以按按钮等...

如果我将 NSURLCONnection 设置为在主线程中运行,即通过删除

[urlConn setDelegateQueue:self.myDownloadQueue];
[urlConn start];

然后代码再次在 IOS5 上运行。但这不是我想要的,我希望下载在后台线程中执行。

我错过了什么?在 IOS5 上是否需要做一些内务处理?当 NSURLConnection 完成时,问题似乎确实发生了,因为 UI 在下载过程中很好。感谢您的帮助 !-A
PS:示例代码可用,只是不想让屏幕过于混乱......

4

0 回答 0