我正在尝试从多个将同时运行的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];
}];
如何设置一个主回调或代理,一旦完成所有数据任务,该调用就会被调用?
最佳答案
您可以使用调度组来侦听所有 call 的结束时间:
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
调用时,notify块才会运行关于ios - 如何聚合来自多个NSURLSessionDataTasks的响应?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33047252/