AFNetworking 依次上传多个文件

AFNetworking Upload multiple files in sequence

我想按顺序上传文件。要上传到服务器一个,然后是第二个等等。 当我 运行 以下代码时,所有文件似乎都被一次加载。此外,我无法在 MBHudProgress 中跟踪进度。

我能否以某种方式做到这一点,以便我从文件加载器得到一个响应,即上一个文件已加载,我可以加载下一个文件吗?

for (id item in imagesArray) {
    NSLog(@"item %@", item);
    NSData *imageData =  UIImagePNGRepresentation(item);

    NSString *urlUpload = @"https://domain/api/wp-json/wp/v2/media?access_token=";
    urlUpload = [urlUpload stringByAppendingString:[Lockbox unarchiveObjectForKey:@"access_token"]];


    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.label.text = @"Uploaded photo";


    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlUpload parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"filename.png" mimeType:@"image/png"];
    } error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {

                      dispatch_async(dispatch_get_main_queue(), ^{

                          hud.progress = uploadProgress.fractionCompleted;
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      [hud hideAnimated:YES];


                      if (error) {
                          NSLog(@"Error: %@", error);
                      } else {
                          NSLog(@"%@ %@", response, responseObject);







                              if ([responseObject objectForKey:@"id"] == nil ||
                                  [[responseObject objectForKey:@"id"] isEqual:[NSNull null]] ||
                                  [responseObject objectForKey:@"id"] == [NSNull null]) {
                                  NSLog(@"NO ID %@", responseObject);
                              } else {
                                  NSLog(@"ID: %@", [responseObject objectForKey:@"id"]);
                                  NSLog(@"source_url: %@", [responseObject objectForKey:@"source_url"]);
                              }






                      }
                  }];

    [uploadTask resume];

}

据我了解,您想一张一张上传图片。上传完第一张图片后,开始上传下一张。

在我看来,您可以在这种情况下使用递归。看看下面我的代码。

// Use recursive to upload an array items
- (void)startUploadItems:(NSMutableArray*)items {
  if (items.count < 1) {
    return;
  }

  [self startUploadItem:items[0] completion:^(BOOL success) {
    [items removeObjectAtIndex:0];

    [self startUploadItems:items];
  }];
}

// Use to upload a single item.
- (void)startUploadItem:(id)item completion:(void(^)(BOOL success))completion {
  NSLog(@"item %@", item);
  NSData *imageData =  UIImagePNGRepresentation(item);

  NSString *urlUpload = @"https://domain/api/wp-json/wp/v2/media?access_token=";
  urlUpload = [urlUpload stringByAppendingString:[Lockbox unarchiveObjectForKey:@"access_token"]];


  MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  hud.mode = MBProgressHUDModeAnnularDeterminate;
  hud.label.text = @"Uploaded photo";


  NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlUpload parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"file" fileName:@"filename.png" mimeType:@"image/png"];
  } error:nil];

  AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

  NSURLSessionUploadTask *uploadTask;
  uploadTask = [manager
                uploadTaskWithStreamedRequest:request
                progress:^(NSProgress * _Nonnull uploadProgress) {

                  dispatch_async(dispatch_get_main_queue(), ^{

                    hud.progress = uploadProgress.fractionCompleted;
                  });
                }
                completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                  [hud hideAnimated:YES];


                  if (error) {
                    NSLog(@"Error: %@", error);
                  } else {
                    NSLog(@"%@ %@", response, responseObject);

                    if ([responseObject objectForKey:@"id"] == nil ||
                        [[responseObject objectForKey:@"id"] isEqual:[NSNull null]] ||
                        [responseObject objectForKey:@"id"] == [NSNull null]) {
                      NSLog(@"NO ID %@", responseObject);
                    } else {
                      NSLog(@"ID: %@", [responseObject objectForKey:@"id"]);
                      NSLog(@"source_url: %@", [responseObject objectForKey:@"source_url"]);
                    }
                  }

                  if (completion) {
                    completion(!error);
                  }
                }];

  [uploadTask resume];
}

用法:

[self startUploadItems:imagesArray];