等待异步api调用完成-Swift/IOS
我正在使用ios应用程序,在我的等待异步api调用完成-Swift/IOS,swift,closures,Swift,Closures,我正在使用ios应用程序,在我的appDelegate中,我有: func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { self.api.signInWithToken(emailstring, token: authtokenstring) { (object: AnyObject
appDelegate
中,我有:
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之前等待调用完成
注意:您不应该这样做,因为它会阻塞线程。查看上面Nate的评论,了解更好的方法
有一种方法可以使用GCD等待异步调用完成。代码如下所示
var semaphore = dispatch_semaphore_create(0)
performSomeAsyncTask {
...
dispatch_semaphore_signal(semaphore)
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
dispatch_release(semaphore)
如果你对信号量一无所知,维基百科会同意的。这是Swift 3中的解决方案。同样,这会阻塞线程,直到异步任务完成,因此只应在特定情况下考虑
let semaphore = DispatchSemaphore(value: 0)
performAsyncTask {
semaphore.signal()
}
// Thread will wait here until async task closure is complete
semaphore.wait(timeout: DispatchTime.distantFuture)
斯威夫特没有这种功能。您需要在
didfishLaunching
的主体中设置窗口和根视图控制器,可能需要一个加载图形,然后在API登录完成处理程序中导航到一个新的视图控制器。didfishLaunching已被弃用,但这听起来是一个不错的主意我尝试了上述方法;苹果已经删除了dispatch\u release(信号量),所以我删除了dispatch\u release(信号量),但是信号量等待似乎阻塞了整个线程。看起来我的异步闭包执行被卡住了。本着学习的精神,你能解释一下为什么我的评论是个坏主意吗?@NateCook相反,我试图表明你的评论包含正确的配方!也许,应该写“如内特所示,使用另一种方法”。抱歉误会了。@brianS当然,它确实会阻塞线程。这正是你一开始问的问题。正如Nate所建议的,只需使用回调来更新UI。