满足一下功能点:
(1)异步上传
(2)所有的请求都完成之后再通知回调
(3)请求返回的结果必须按照请求发出的数据顺序一致
- (NSURLSessionUploadTask*)uploadTaskWithImage:(UIImage*)image completion:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionBlock {
// 构造 NSURLRequest
NSError* error = NULL;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[self uploadUrl] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
[formData appendPartWithFileData:imageData name:@"file" fileName:@"someFileName" mimeType:@"multipart/form-data"];
} error:&error];
// 将 NSURLRequest 与 completionBlock 包装为 NSURLSessionUploadTask
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
} completionHandler:completionBlock];
return uploadTask;
}
- (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);
NSURLSessionUploadTask* uploadTask = [self uploadTaskWithImage:images[i] completion:^(NSURLResponse *response, NSDictionary* responseObject, NSError *error) {
if (error) {
NSLog(@"第 %d 张图片上传失败: %@", (int)i + 1, error);
dispatch_group_leave(group);
} else {
NSLog(@"第 %d 张图片上传成功: %@", (int)i + 1, responseObject);
@synchronized (result) { // NSMutableArray 是线程不安全的,所以加个同步锁
result[i] = responseObject; //block会保存自动变量
}
dispatch_group_leave(group);
}
}];
[uploadTask resume];
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"上传完成!");
for (id response in result) {
NSLog(@"%@", response);
}
});
}