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

时间:2014-11-06 20:04:43

标签: swift closures

我正在开发一个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之前等待它完成。

2 个答案:

答案 0 :(得分:11)

  

注意:你应该这样做,因为它会阻止线程。请参阅上面的Nate评论以获得更好的方法。

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

var semaphore = dispatch_semaphore_create(0)

performSomeAsyncTask {
    ...
    dispatch_semaphore_signal(semaphore)
}

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
dispatch_release(semaphore)

如果你对信号量一无所知,维基百科就有了article

答案 1 :(得分:1)

这是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)