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

爱⌒轻易说出口 提交于 2019-12-08 00:23:36

问题


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.


回答1:


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.




回答2:


Swift Version of @Kamran :

let group = DispatchGroup()
for model in self.cellModels {

    group.enter()

    HTTPAPI.call() { (result) in

        // DO YOUR CHANGE
        switch result {
           ...
        }
        group.leave()
    }
}
group.notify(queue: DispatchQueue.main) {
     // UPDATE UI or RELOAD TABLE VIEW etc.
     // self.tableView.reloadData()
}



回答3:


I suppose your request is due to the fact that you might have huge amounts of queued delete requests, not just five or ten of them. In this case, I'd also try and consider adding a server side API call that allows you to delete more than just one item at a time, maybe up to ten or twenty, so that you could also reduce the overhead of the network traffic you'd be generating (a single GET isn't just sending the id of the item you are deleting but also a bunch of data that will basically sent on and on again for each and every call) by grouping the mails in batches.



来源:https://stackoverflow.com/questions/51735995/ios-afnetwork-3-0-is-there-a-faster-way-to-send-multiple-api-requests-and-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!