How to aggregate response from multiple NSURLSessi

2019-07-14 05:47发布

问题:

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