Reputation: 391
I've the following code below (example code) that sends an API GET request multiple times.
- (void)listOfPeople:(NSArray *)array {
for (int i = 0; i < array.count; i++) {
Person *person = [array objectAtIndex:i];
[personClient getPersonData:person.fullName onSuccess:^(id result) {
// change data here
} onFailure:^(NSError *error) {
}];
}
}
The code doesn't work very well because the API requests finishes in a different order every time. I need to complete each api request in order. I believe I need to wait until either the completion block or the failure block is finished before continuing the for loop. Can someone point me in the right direction unless there is a better way to accomplish this task. I've tried dispatch group, but it didn't complete each request in order.
Upvotes: 1
Views: 476
Reputation: 4174
Get rid of the for
loop, and instead make a recursive function that calls itself from the completion handler to get the next Person. That way when each call completes, it will make the call to get the next one.
Something like this:
- (void)getPersonFromArray:(NSArray *)array atIdx:(NSInteger)idx {
if (idx < array.count)
{
Person *person = [array objectAtIndex:idx];
[personClient getPersonData:person.fullName onSuccess:^(id result)
{
// Do something useful with Person here...
// ...
[self getPersonFromArray:array atIdx(idx + 1)];
} onFailure:^(NSError *error) {
// Handle errors here
// ...
}];
}
}
Upvotes: 0