iosobjective-chttprequestafnetworking-3

iOS AFNetwork 3.0: Is there a faster way to send multiple API requests and wait until all of it is finished?


I am currently using the following method to send GET API requests. This method works, but I was wondering if there is a faster way. All I need regarding requirements is to know when all of the Deleted mail has been synced. Any tips or suggestions are appreciated.

- (void)syncDeletedMail:(NSArray *)array atIdx:(NSInteger)idx {
    if (idx < array.count) {
        NSInteger idNumber = array[idx];

        [apiClient deleteMail:idNumber onSuccess:^(id result) {
            [self syncDeletedMail:array atIdx:(idx + 1)];
        } onFailure:^(NSError *error){
            [self syncDeletedMail:array atIdx:(idx + 1)];
        }];
    } else {
       NSLog(@"finished");
    }
}

Edit: I don't care what order it is completed (not sure if it matters in terms of speed), as long as all the API requests come back completed.


Solution

  • You can just send deleteMail requests at once and use dispatch_group to know when all the requests are finished. Below is the implementation,

    - (void)syncDeletedMail:(NSArray *)array {
    
        dispatch_group_t serviceGroup = dispatch_group_create();
    
        for (NSInteger* idNumber in array)
        {
            dispatch_group_enter(serviceGroup);
            [apiClient deleteMail:idNumber onSuccess:^(id result) {
                dispatch_group_leave(serviceGroup);
            } onFailure:^(NSError *error){
                dispatch_group_leave(serviceGroup);
            }];
        }
    
        dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
           NSLog(@"All email are deleted!"); 
        });
    }
    

    Here you can see all the requests are fired at the same time so it will reduce the time from n folds to 1.