AFNetwork 2.0 Queue with completion block?

2019-02-11 03:36发布

How do I create a queue on AFNetwork 2.0 and set a completion handler for when the added oppertations are finished?

currently I have this

ASINetworkQueue *queue = [[ASINetworkQueue alloc] init];

[queue setDelegate:self];
[queue setQueueDidFinishSelector:@selector(refeshInterface)];

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[queue addOperation:request];

ASIFormDataRequest *request2 = [ASIFormDataRequest requestWithURL:url2];
[queue addOperation:request2];

[queue go]

But I need to convert it to AFNetwork. All the solutions I have found so far seem to use AFHTTPClient which doesn't exist in AFNetwork 2.0.

I am new to AFNetwork, so some examples would be greatly appreciated.

Thanks!

1条回答
Lonely孤独者°
2楼-- · 2019-02-11 03:57

You need

+ (NSArray *)batchOfRequestOperations:(NSArray *)operations
                        progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
                      completionBlock:(void (^)(NSArray *operations))completionBlock

method of AFURLConnectionOperation.

Please look at the following sample

NSMutableArray *operations = [NSMutableArray array];

for (DGSocialImage *socialImage in socialImages) {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:socialImage.url];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFImageResponseSerializer new];
    [operations addObject:operation];
}
NSArray *batchOperations = [AFURLConnectionOperation batchOfRequestOperations:operations
                                                                progressBlock:NULL
                                                              completionBlock:^(NSArray *operations) {
    NSError *error;
    for (AFHTTPRequestOperation *op in operations) {
        if (op.isCancelled){
            return ;
        }
        if (op.responseObject){
            // process your responce here
        }
        if (op.error){
            error = op.error;
        }
    }
}];
[[NSOperationQueue mainQueue] addOperations:batchOperations waitUntilFinished:NO];
查看更多
登录 后发表回答