加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:57:14 所属栏目:百科 来源:网络整理
导读:我正在开发一个ios应用程序,我的appDelegate中有: func application(application: UIApplication!,didFinishLaunchingWithOptions launchOptions: NSDictionary!) - Bool { self.api.signInWithToken(emailstring,token: authtokenstring) { (object: AnyOb
我正在开发一个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,如果您对信号量一无所知.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读