我正在尝试聚合来自多个同时运行的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];
}];
如何在完成所有数据任务后调用主回调或委托来设置它?
答案 0 :(得分: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
来电之前,通知功能块才会运行