gpt4 book ai didi

swift - 等到异步 api 调用完成 - Swift/IOS

转载 作者:搜寻专家 更新时间:2023-10-30 22:26:33 25 4
gpt4 key购买 nike

我正在开发一个 ios 应用程序,在我的 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。

最佳答案

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

有一种方法可以使用 GCD 等待异步调用完成。代码如下所示

var semaphore = dispatch_semaphore_create(0)

performSomeAsyncTask {
...
dispatch_semaphore_signal(semaphore)
}

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
dispatch_release(semaphore)

维基百科有一个 OK article如果您对信号量一无所知。

关于swift - 等到异步 api 调用完成 - Swift/IOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26788434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com