0

I have an app that the first thing it does is to register itself in an API, with a simple HTTP POST. I've been doing this in func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?), as Apple states that this is the point do to URL calls. As it is important to never block the main thread, this call is done async.

The problem is that as it is done async, the first screen opens and immediately a call to the API is done. As this is faster then the first API call, the second call gets a 401.

In order to avoid that, I am doing a very cheesy thing before starting the second call:

dispatch_async(dispatch_get_global_queue(priority, 0)) {
    // do some task
    while (InformationFromFirsCall == nil)
    {
        sleep(1)
    }
}

Is there a better strategy to do this? I was thinking about using a dispatch_once at the beginning of every call to the API and implementing the code inside the callback of InformationFromFirstCall.

Is that reasonable?

Thanks!

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
Rafa Borges
  • 576
  • 1
  • 7
  • 17
  • 4
    Why not put up a loading screen and wait for the first registration API call to finish? – jestro May 13 '15 at 02:32
  • @jestro, this is not a bad idea, but the reason why I'am using asyn at first place is exactly to not keep the user waiting and allow him to experience the app while things run at the background. – Rafa Borges May 13 '15 at 11:00

1 Answers1

0

Instead of using sleep, you can save CPU time by using a semaphore:

// declared somewhere where you can access it
dispatch_semaphore_t sema;

// willFinishLaunching
sema = dispatch_semaphore_create(0);

// when your async call completes
dispatch_semaphore_signal(sema);

// in your main UI — this is the same as the sleep call you have, but doesn't waste CPU time
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

A semaphore is an efficient mechanism for forcing one part of your app to wait while another app is doing something — a call to dispatch_semaphore_wait causes the current thread to hang until the semaphore's value becomes non-zero, which happens when dispatch_semaphore_signal is called.

See this answer for more details.

Note: this is C code; you will need to adapt it to Swift syntax if you are coding your app in Swift.

Community
  • 1
  • 1
Greg
  • 9,068
  • 6
  • 49
  • 91