完成几个异步NSURLConnections后执行操作

时间:2015-02-18 21:48:09

标签: ios objective-c cocoa-touch asynchronous nsurlconnection

我有一个 iOS 应用,可执行返回JSON数组网址的HTTP请求:

[NSURLConnection sendAsynchronousRequest:request
                                       queue:[[NSOperationQueue alloc] init]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                               NSError *jsonError = nil;
                               NSDictionary *JSON = [NSJSONSerialization
                                                     JSONObjectWithData: data
                                                     options: NSJSONReadingMutableContainers
                                                     error: &jsonError];

其中JSON是格式的字典:

{
  "url1" : "http://example.com/downloadfile1.bin",
  "url2" : "http://example.net/downloadfile2.bin",
  "url3" : "http://example.org/downloadfile3.bin"
}

现在我需要循环遍历字典并下载每个文件(在这种情况下,每个URL对应于密钥:url1url2url3)。所以我在字典键上使用嵌套[NSURLConnection sendAsynchronousRequest:]来尝试这个。

我的问题是,我需要在所有嵌套URL下载完成后触发事件。然而,由于它们是异步的,我不知道如何判断所有文件的下载时间。

我看到我可以使用:

NSOperationQueue *queue = [NSOperationQueue mainQueue];
[queue setMaxConcurrentOperationCount:1];

为了强制连续运行这些HTTP请求,但我仍然不确定如何判断它们何时完成。或者我是否必须计算循环,然后观察要触发的“最后”请求。对我来说似乎是一个非常讨厌的解决方案。

有谁知道如何更好地做到这一点?如何执行多个 HTTP 请求并知道它们何时完成?另外,我不想同步执行此操作,因为我不想阻止主线程。

0 个答案:

没有答案