等待异步api调用完成 - Swift / IOS [英] Wait until an asynchronous api call is completed - Swift/IOS
本文介绍了等待异步api调用完成 - Swift / IOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在一个ios应用程序,在我的appDelegate我有:
I'm working on an ios app 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是一个使用Alamofire进行的异步调用,我想在func应用程序的末端返回true之前等待它完成。
The api.signInWithToken is an asynchronous call made with Alamofire, and I would like to wait for it's completion before returning true at the end end of func application.
推荐答案
注意:您应该不这样做,因为它阻止了线程。
Note: You should not do it this way, as it blocks the thread. See Nate's comment above for a better way.
有一种方法可以等待异步调用使用GCD完成。代码如下所示
There is a way to wait for an async call to complete using GCD. The code would look like the following
var semaphore = dispatch_semaphore_create(0)
performSomeAsyncTask {
...
dispatch_semaphore_signal(semaphore)
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
dispatch_release(semaphore)
维基百科有一个确定文章,以防您对信号量无所知晓。
Wikipedia has an OK article in case you know nothing about semaphores.
这篇关于等待异步api调用完成 - Swift / IOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文