1

Trying to replace deprecated sendSynchronousRequest calls in several command line tools I have written. The completionHandler is not getting called. Based on somewhat similar questions, I have tried using a semaphore, but still no joy. (Most questions posted concern apps, not command line tools.) Appreciate any help. Here's my code snippet:

void ebayApiCall(NSMutableURLRequest * request, NSError *error) {

    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
                                   ^(NSData *data, NSURLResponse *response, NSError *error) {
                                       NSLog(@"\nCompletionHandler\n");
                                       responseFromEbay = data; //responseFromEbay is global
                                       dispatch_semaphore_signal(sema);
                                   }];

    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    [dataTask resume];
}
rick
  • 51
  • 6

1 Answers1

0

You just have to call [dataTask resume] before waiting on the semaphore.

0xced
  • 25,219
  • 10
  • 103
  • 255
  • This fixed it! Thanks! Wonder how the example I found this from ever worked? (Sorry I don't have enough points to up vote you :-( – rick Mar 20 '16 at 21:30
  • Since I made the switch to use NSURLSessionDataTask, I have started to receive occasional error messages like: "INFO: fetch-response is unable to open the file /Users/rick/Library/Caches/EbayPricing/fsCachedData/B401D746-49F1-4980-BD67-7AD0DC0E4D47. Errno: 2" Any ideas on this? I never got that error before switching from synchronous calls to async calls. I put a 1 second delay after the [datatask resume] and it reduced the frequency of the errors, but it also slows my program! – rick Mar 25 '16 at 00:02