mergesort mergesort - 3 months ago 25
iOS Question

How can an NSOperationQueue wait for two async operations?

How can I make an NSOperationQueue (or anything else) wait for two async network calls with callbacks? The flow needs to look like this

Block Begins {
Network call with call back/block begins {
first network call is done
}
}
Second Block Begins {
Network call with call back/block begins {
second network call is done
}
}

Only run this block once the NETWORK CALLS are done {
blah
}


Here's what I have so far.

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
__block NSString *var;


[queue addOperation:[NSBlockOperation blockOperationWithBlock:^{
[AsyncReq get:^{
code
} onError:^(NSError *error) {
code
}];
}]];

[queue addOperation:[NSBlockOperation blockOperationWithBlock:^{
[AsyncReq get:^{
code
} onError:^(NSError *error) {
code
}];
}]];
[queue waitUntilAllOperationsAreFinished];
//do something with both of the responses

Answer

Do you have to use NSOperation Queue? Here's how you can do it w/ a dispatch group:

dispatch_group_t group = dispatch_group_create();

dispatch_group_enter(group);
[AsyncReq get:^{
    code
    dispatch_group_leave(group); 
} onError:^(NSError *error) {
    code
    dispatch_group_leave(group);
}];


dispatch_group_enter(group);
[AsyncReq get:^{
    code
    dispatch_group_leave(group); 
} onError:^(NSError *error) {
    code
    dispatch_group_leave(group);
}];

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    NSLog(@"Both operations completed!")
});