AFNetworking按顺序上传多个文件

时间:2018-04-10 19:02:31

标签: ios objective-c xcode afnetworking

我想按顺序上传文件。要上传到服务器一个,然后是第二个,依此类推。 当我运行以下代码时,所有文件似乎一次加载。另外,我无法跟踪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];

}

1 个答案:

答案 0 :(得分:1)

据我了解,您希望逐个上传图片。上传第一张图片后,开始上传下一张图片。

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

// 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];