• 批量上传图片


    满足一下功能点:

    (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);
    }
    });
    }

  • 相关阅读:
    cf1270D——交互,思维
    cf1270E —— 奇偶构造!+ 坐标系分类讨论旋转
    cf1207E——交互,思维
    cf1271D——经典 dp+贪心+图论
    cf1271E——数学找规律,二分套二分
    cf1272E——bfs反边图
    cf1272F——经典升维dp,好题!
    cf1276B——割点+深搜树
    cf1276C——单调性分析,思维
    cf1277D——思维贪心+字符串
  • 原文地址:https://www.cnblogs.com/jinlongyu123/p/10418569.html
Copyright © 2020-2023  润新知