2

我正在尝试从将同时运行的多个 NSURLSessionDataTasks 中聚合数据。

__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];
}];

如何使用在所有数据任务完成后调用的主回调或委托进行设置?

4

1 回答 1

7

您可以使用调度组来监听所有呼叫何时完成:

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

通知块不会运行,直到有dispatch_group_leave每个调用dispatch_group_enter

于 2015-10-09T21:27:24.177 回答