我正在使用AFNetworking代码来批量处理请求.我真的从示例代码中复制和粘贴 - 看起来像这样:
NSMutableArray *mutableOperations = [NSMutableArray array]; for (NSURL *fileURL in filesToUpload) { NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(idformData [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil]; }]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [mutableOperations addObject:operation]; } NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperation 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];
现在我想要实现的是在第一个队列失败时取消该队列中的所有其他操作.
我找到了一个带有AFHttpClient的1.0.3的解决方案但是没有2.0的解决方案.
有小费吗 ?
而不是将操作添加到[NSOperationQueue mainQueue]
,创建自己的操作队列.所以,在你@interface
定义一个队列时:
@property (nonatomic, strong) NSOperationQueue *networkQueue;
然后,实例化一个队列:
self.networkQueue = [[NSOperationQueue alloc] init]; self.networkQueue.name = @"com.domain.app.networkqueue"; // if you want it to be a serial queue, set maxConcurrentOperationCount to 1 // // self.networkQueue.maxConcurrentOperationCount = 1; // // if you want it to be a concurrent queue, set it to some reasonable value // // self.networkQueue.maxConcurrentOperationCount = 4;
然后,将您的网络操作添加到此队列(绕过batchOfRequestOperations
):
NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"All operations done"); }]; // NSOperation *previousOperation = nil; // if you uncomment dependency code below, uncomment this, too 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]; // if you want the operations to run serially, you can also // make each dependent upon the prior one, as well // // if (previousOperation) // [operation addDependency:previousOperation]; // // previousOperation = operation; [completionOperation addDependency:operation]; [self.networkQueue addOperation:operation]; } [self.networkQueue addOperation:completionOperation];
最后,如果要取消操作,可以执行以下操作:
[self.networkQueue cancelAllOperations];