How to aggregate response from multiple NSURLSessionDataTasks?

依然范特西╮ 提交于 2020-01-05 03:11:20

问题


I am trying to aggregate the data from multiple NSURLSessionDataTasks that will run concurrently.

__block NSMutableDictionary *languageDetails = [NSMutableDictionary new];
[repos enumerateObjectsUsingBlock:^(NSDictionary *repoDict, NSUInteger idx, BOOL * _Nonnull stop) {
    NSString *languageUrl = repoDict[@"languages_url"];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:languageUrl]
                                                             completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                                 // JSON Parse response
                                                                 // Update languageDetails
                                                             }];
    [task resume];
}];

How do I set this up with a master callback or delegate that gets called once all the data tasks are done?


回答1:


You can use a dispatch group to listen for when all the calls are finished:

dispatch_group_t tasks = dispatch_group_create();

__block NSMutableDictionary *languageDetails = [NSMutableDictionary new];
[repos enumerateObjectsUsingBlock:^(NSDictionary *repoDict, NSUInteger idx, BOOL * _Nonnull stop) {
    dispatch_group_enter(tasks);

    NSString *languageUrl = repoDict[@"languages_url"];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:languageUrl]
                                                             completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                                 // JSON Parse response
                                                                 // Update languageDetails

                                                                 dispatch_group_leave(tasks);
                                                             }];
    [task resume];
}];

dispatch_group_notify(tasks, dispatch_get_main_queue(), ^{
    // All the tasks are done, do whatever
});

The notify block won't get run until there is a dispatch_group_leave call for every dispatch_group_enter



来源:https://stackoverflow.com/questions/33047252/how-to-aggregate-response-from-multiple-nsurlsessiondatatasks

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