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.