iOS AFNetwork 3.0: Is there a faster way to send m

2019-05-27 14:49发布

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.

3条回答
倾城 Initia
2楼-- · 2019-05-27 15:10

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.

查看更多
时光不老,我们不散
3楼-- · 2019-05-27 15:24

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()
}
查看更多
不美不萌又怎样
4楼-- · 2019-05-27 15:25

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.

查看更多
登录 后发表回答