Wait for asynchronous api call to complete - Swift / IOS

I am working on an ios application where in my appDelegate I have:

 func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { self.api.signInWithToken(emailstring, token: authtokenstring) { (object: AnyObject?, error:String?) in if(object != nil){ self.user = object as? User // go straight to the home view if auth succeeded var rootViewController = self.window!.rootViewController as UINavigationController let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var homeViewController = mainStoryboard.instantiateViewControllerWithIdentifier("HomeViewController") as HomeViewControllerenter // code here rootViewController.pushViewController(homeViewController, animated: true) } } return true } 

api.signInWithToken is an asynchronous call made using Alamofire, and I would like to wait for it to complete before returning true at the end of the func application.

+5
source share
2 answers

Note. You should not do it this way, as it blocks the thread. See Nate Comment above for a better way.

There is a way to wait for an asynchronous call to complete using a GCD. The code will look like this

 var semaphore = dispatch_semaphore_create(0) performSomeAsyncTask { ... dispatch_semaphore_signal(semaphore) } dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) dispatch_release(semaphore) 

Wikipedia has an article if you don't know anything about semaphores.

+11
source

This solution is in Swift 3. Again, it blocks the thread until the asynchronous task completes, so it should be considered only in specific cases.

 let semaphore = DispatchSemaphore(value: 0) performAsyncTask { semaphore.signal() } // Thread will wait here until async task closure is complete semaphore.wait(timeout: DispatchTime.distantFuture) 
+1
source

Source: https://habr.com/ru/post/1206364/


All Articles