2015-06-21 64 views
1

我已经创建了一个导航控制器,并将其分配给我在Swift中的View Controller。为什么导航控制器不使用Swift在回调中导航?

我创建了以下方法:

@IBAction func btnLoginPressed(sender: AnyObject) { 
    let userManager = UserManager() 
     userManager.login(txtBoxLogin.text, password: txtBoxPassword.text, operationCompleteHandler: { 
      (token: String?) -> Void in 
       if let token = token { 
        ApplicationState.ApiToken = token 
        var mainView = self.storyboard?.instantiateViewControllerWithIdentifier("MenuView") as! MenuViewController 
        self.navigationController!.pushViewController(mainView, animated: true) 
       } 
     }) 
} 

的问题是,它并没有在这个配置下工作。但是,如果我把

self.storyboard?.instantiateViewControllerWithIdentifier("MenuView") as! MenuViewController 
        self.navigationController!.pushViewController(mainView, animated: true) 

operationCompleteHandler它的工作完美无瑕。

我在做什么错,我应该如何解决这个问题?

回答

1

最后,我发现了这种奇怪行为的原因:回调运行在与UI线程分离的线程上。

为了让一段代码做UI相关的事情,你必须使用dispatch_async()方法。这里是我使用提到的方法进行工作导航的更新代码:

@IBAction func btnLoginPressed(sender: AnyObject) { 
    let userManager = UserManager() 
     userManager.login(txtBoxLogin.text, password: txtBoxPassword.text, operationCompleteHandler: { 
      (token: String?) -> Void in 
       if let token = token { 
        ApplicationState.ApiToken = token 
        dispatch_async(dispatch_get_main_queue()) { 
         var mainView = self.storyboard?.instantiateViewControllerWithIdentifier("MenuView") as! MenuViewController 
         self.navigationController!.pushViewController(mainView, animated: true) 
        } 
       } 
     }) 
} 
+0

好找的人。你已经救了我几个小时。我仍在学习。谢谢。 – Rezoan