Lor*_*o B 2 networking nsurlconnection nsoperationqueue ios http-request
我在设置相对于sendAsynchronousRequest:queue:completionHandler:方法(NSURLConnection类)的正确配置方面遇到了一些困难.
我的方案如下:
我建立了一个管理不同NSURLConnections 的单例类.这个单例符号有一个NSOperation Queue(被叫downloadQueue),它向Web服务器发出请求并检索字符串路径(1).完成后,该路径用于下载Web服务器(2)中的文件.最后,当文件被正确下载后,我需要更新UI(3).
我只想出了第一个请求:我可以通过它下载路径.你能建议我一个方法来执行其他两个步骤吗?
这里几个问题:
下载队列(downloadQueue)不是主要的,是否可以在该队列中打开新的NSURLConnection?换句话说,这是正确的吗?(参见代码片段中的注释)
如果前一个问题是正确的,我如何获取主队列并更新UI?
这里我用来执行第一步的代码片段downloadQueue是一个可以通过访问器方法获得的实例变量(@property/ @synthesized);
// initializing the queue...
downloadQueue = [[NSOperation alloc] init];
// other code here...
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[self downloadQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if([data length] > 0 && error == nil) {
// here the path (1)
// how to perform a second connection?
// what type of queue do I have to use?
}
}];
Run Code Online (Sandbox Code Playgroud)
您正在进行首次下载.
在第一次下载后的完成处理程序块中,您正在计算第二次下载所需的URL,对吧?然后,您可以以相同的方式执行第二次下载:+[NSURLConnection sendAsynchronousRequest:...]使用新URL和相同的队列再次调用.您可以在完成块中执行此操作以进行首次下载.
要在第二次下载完成后更新UI,请切换到完成块中的主队列以进行下载.你可以做到这一点dispatch_async()还是dispatch_sync()和(在这种情况下,因为你没有进一步的工作要做下载队列不要紧哪个)dispatch_get_main_queue(),或-[NSOperationQueue addOperationWithBlock:]和+[NSOperationQueue mainQueue].
您的代码应如下所示:
// init download queue
downloadQueue = [[NSOperationQueue alloc] init];
// (1) first download to determine URL for second
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[self downloadQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if([data length] > 0 && error == nil) {
// set newURLRequest to something you get from the data, then...
// (2) second download
[NSURLConnection sendAsynchronousRequest:newURLRequest queue:[self downloadQueue] completionHandler:^(NSURLResponse *newResponse, NSData *newData, NSError *newError) {
if([newData length] > 0 && newError == nil) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// (3) update UI
}];
}
}];
}
}];
Run Code Online (Sandbox Code Playgroud)