- (IBAction)runDispatchTest:(id)sender {
// 需要上传的数据
NSArray* images = [self images];
// 准备保存结果的数组,元素个数与上传的图片个数相同,先用 NSNull 占位
NSMutableArray* result = [NSMutableArray array];
for (UIImage* image in images) {
[result addObject:[NSNull null]];
}
dispatch_group_t group = dispatch_group_create();
for (NSInteger i = 0; i < images.count; i++)
{
dispatch_group_enter(group);
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLSessionUploadTask* uploadTask = [self uploadTaskWithImage:images[i] completion:^(NSURLResponse *response, NSDictionary* responseObject, NSError *error) {
if (error)
{
NSLog(@"第 %d 张图片上传失败: %@", (int)i + 1, error);
} else
{
NSLog(@"第 %d 张图片上传成功: %@", (int)i + 1, responseObject);
@synchronized (result)
{ // NSMutableArray 是线程不安全的,所以加个同步锁
result[i] = responseObject;
}
}
dispatch_group_leave(group);
}];
[uploadTask resume];
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"上传完成!");
for (id response in result) {
NSLog(@"%@", response);
}
});
}
网友评论