-1

In my case, when an App launches, I want to call 3 web APIs using NSURLSessionDataTask. I have 3 different methods for each API and inside each method, there is one NSURLSessionDataTask.

I want to shape my code in such a way that these 3 methods execute serially. Because, method B is depended on method A's response and method C is depended on method B's response. Each method also doing some database operation after getting API response. So, I need serial execution of methodA, methodB and methodC.

I know this is a logical thing but I want to use dispatch_semaphore_t or dispatch_group_wait but I have absolutely no clue on how I can use those in a conjuction with NSURLSessionDataTask.

I have tried with this:

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    [self syncA:^(BOOL success) {

        NSLog(@"syncA — Completed");
        dispatch_semaphore_signal(semaphore);
    }];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    [self syncB:^(BOOL success) {

        NSLog(@"syncB — Completed");
        dispatch_semaphore_signal(semaphore);
    }];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    [self syncC:^(BOOL success) {

        NSLog(@"syncC — Completed");
        dispatch_semaphore_signal(semaphore);
    }];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    NSLog(@"************* END OF SYNC *************");

The above code is stuck on first method.

halfer
  • 19,824
  • 17
  • 99
  • 186
NSPratik
  • 4,714
  • 7
  • 51
  • 81
  • 1
    use NSOperationQueue for any serial operations. – Gagan_iOS Mar 29 '16 at 12:20
  • Conceptually, `NSURLSession` is an operation queue !!! – NSPratik Mar 29 '16 at 12:22
  • 1
    look into this question http://stackoverflow.com/questions/21198404/nsurlsession-with-nsblockoperation-and-queues – Gagan_iOS Mar 29 '16 at 12:25
  • 1
    @Gagan_iOS This answer is no suitable approach for the OPs problem: first, you need three subclasses of NSOperation, and once you have those implemented, there's still no easy way to pass output data from Op1 to input to Op2 etc. This approach becomes that cumbersome and laborious, that it is undoable in practice. – CouchDeveloper Apr 14 '16 at 23:17
  • 1
    @CouchDeveloper thanks for update. – Gagan_iOS Apr 15 '16 at 10:40

1 Answers1

2

Are you using those in main queue? Do not run the callback blocks in the same queue as dispatch_semaphore_wait, because dispatch_semaphore_wait will block the queue and the callback will not be executed, which will cause dead lock.

Bing
  • 351
  • 3
  • 12