我正在使用AFNetworking代码来批量处理请求。我真的有副本&从示例代码粘贴 - 它看起来像:
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: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];
现在我想要实现的是取消第一个队列中的所有其他操作。
我找到了一个1.0.3的AFHttpClient解决方案,但没有2.0的解决方案。
任何提示?
答案 0 :(得分:5)
不是将操作添加到[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];