1

I have an iOS app that performs an HTTP request that returns a JSON array of URLs:

[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];

Where JSON is a dictionary of the format:

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

Now I need to loop over the dictionary and download each of the files (in this case, each URL corresponding to the keys:url1, url2, and url3). So I'm trying this with a nested [NSURLConnection sendAsynchronousRequest:] over the dictionary keys.

My issue is that I need to fire an event when all the nested URL downloads are complete. Yet, since they are asynchonous, I don't know how to tell when all the files are downloaded.

I see I can use:

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

In order to force running these HTTP requests in serial, but I still am not sure how to tell when they all complete. Or would I have have to count the loops and then watch for the "last" request to be fired. Seems like a pretty hacky solution to me.

Does anyone have any idea how to better do this? How can I perform several HTTP requests and know when they all finish? Also, I don't want to do this synchronously because I don't want to block the main thread.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Brett
  • 11,637
  • 34
  • 127
  • 213
  • This is not a duplicate to the referenced question. That question is specific to AFNetworking, which I am not using. – Brett Feb 18 '15 at 22:41
  • The answer there does not require AFNetworking at all. Just replace the `AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1]; [operation1 setCompletionBlockWithSuccess:` bits with your `NSURLConnection` creation and you should be all set. – jscs Feb 18 '15 at 23:18
  • 2
    The accepted answer in the link ["This question already has an answer here:"](http://stackoverflow.com/questions/10643797/wait-until-multiple-networking-requests-have-all-executed-including-their-comp) is suboptimal since it uses a blocking approach and does not provide a solution for cancellation (which is strongly recommended in the OPs use case). – CouchDeveloper Feb 19 '15 at 05:39

0 Answers0