是否可以同时使用[AFURLConnectionOperation batchOfRequestOperations ...]和setUploadProgressBlock?

时间:2014-08-08 05:25:13

标签: objective-c ios7 afnetworking-2

我正如here所述使用AFURLConnectionOperation batchOfRequestOperations。我的代码是下面示例代码的修改版本,它可以工作。

NSMutableArray *mutableOperations = [NSMutableArray array];
for (NSURL *fileURL in filesToUpload) {
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [mutableOperations addObject:operation];
}

NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
    NSLog(@"All operations in batch complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

我遇到的问题是,我无法弄清楚如何单独使用AFURLConnectionOperation类,特别是setUploadProgressBlock,其定义如下:

- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block;

问题是batchOfRequestOperations是静态方法,需要在实例上定义进度块。我无法找到设置AFURLConnectionOperation并将其用作实例的任何示例(除了请求,我不想要)。即使我可以,我也想重新创建我正在使用的批处理方法的功能。

有没有办法同时使用这个非常方便的块和非常方便的批处理方法?如果没有,我会接受其他建议......

tl; dr:我想批量处理一些上传操作,并使用简单的进度块来跟踪他们的进度。

1 个答案:

答案 0 :(得分:3)

您可以在batchOfRequestOperations中获取每个操作并使用它们:

[AFURLConnectionOperation batchOfRequestOperations:operations 
 progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) 
 {
     for(AFHTTPRequestOperation *operation in operations)
     {
         [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                        long long totalBytesWritten,
                                        long long totalBytesExpectedToWrite) {
         NSLog(@"PROGRESS: %lld TOTAL: %lld", totalBytesWritten, totalBytesExpectedToWrite);
         //Do whatever you want with the progress
         }];
     }
  }

completionBlock:^(NSArray *operations) {}
];

现在您已经获得了每个请求的进度,您可以轻松地存储和增加全局进度的值。