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

无人久伴 提交于 2019-12-06 04:35:51

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.

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()
}

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.

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