如何聚合来自多个NSURLSessionDataTasks的响应?
我正在尝试聚合来自多个同时运行的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]; }];
如何在完成所有数据任务后调用主回调或委托来设置它?
所有调用完成后,您可以使用调度组来侦听:
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_enter
都有dispatch_group_enter
调用之前,通知块不会运行