Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for multiple AFNetworking requests to complete

I need to wait for several AFNetworking requests to complete, i tried using dispatch groups, but I can't seem to get it right.

Here's my code:

dispatch_group_t group = dispatch_group_create();

for (int k = 0; k < 10 ; k++) {
    dispatch_group_enter(group);

    [[AFHTTPSessionManager manager] GET:@"http://google.com/" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success");
        dispatch_group_leave(group);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure");
        dispatch_group_leave(group);
    }];
}

dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

NSLog(@"DONE");

The problem is that it gets stuck on dispatch_group_wait, because neither the success block, nor the failure blocks are called.

How can I solve it?

like image 841
guidev Avatar asked Apr 24 '16 13:04

guidev


1 Answers

The dispatch queue for completionBlock. If NULL (default), the main queue is used.

dispatch_group_t group = dispatch_group_create();

dispatch_queue_t queue = dispatch_queue_create("com.app", DISPATCH_QUEUE_CONCURRENT);

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.completionQueue = queue;
for(int k = 0; k < 10; k++) {
    dispatch_group_enter(group);

    dispatch_async(queue, ^{
        NSLog(@"%d", k);
        [manager GET:@"http://baidu.com/" parameters:nil progress:nil success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
             NSLog(@"success");
             dispatch_group_leave(group);
         } failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error) {
             NSLog(@"failure");
             dispatch_group_leave(group);
         }];
    });
}

dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

NSLog(@"DONE");
like image 52
酷酷的哀殿 Avatar answered Sep 21 '22 12:09

酷酷的哀殿