Reputation: 8091
So I am browsing over Stack Overflow for ways to handle asynchronous requests effectively. Right now I am using ASIHTTPRequest and my application consumes a REST API, in which a request to a single resource prompts me to request 5 or more additional resources (linked resources).
Right now I am doing all asynchronous request inside one huge method, there may be around 6 asynchronous request each with their setCompletionBlock and setFailBlock. If you have used ASIHTTPRequest, you must have an idea of how much repetitive code that will take.
Anyway, I seem to have found a solution to determine if all requests are finished with this answer: Multiple asynchronous URL requests
however, I don't know how to apply that answer in code ,as I have not used push notifications before and I have always used "self" as delegats and never other classes.
Any ideas how I can apply the answer to code or better yet, do you know of any other methods?
Thanks in advance!
Upvotes: 6
Views: 7901
Reputation: 112857
Use a GCD group with dispatch_group_wait.
Example:
__block NSMutableArray *imageURLList = [NSMutableArray array];
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
for (Helper *siteURL in list) {
dispatch_group_async(group, queue, ^{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:siteURL]];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (urlData.length)
[imageURLList urlData];
});
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
Note that the block is executed async so it is alright to use sendSynchronousRequest:
.
Upvotes: 3
Reputation: 16714
Put all the requests into an ASINetworkQueue: http://allseeing-i.com/ASIHTTPRequest/How-to-use#about_ASINetworkQueues.
ASINetworkQueue has a callback called "queueDidFinishSelector".
Upvotes: 4