I have created a navigation controller and assigned it to my View Controller in Swift.
I created the following method:
@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)
}
})
}
The problem is that it does not work in this configuration. However if I put
self.storyboard?.instantiateViewControllerWithIdentifier("MenuView") as! MenuViewController
self.navigationController!.pushViewController(mainView, animated: true)
outside the operationCompleteHandler it works flawlessly.
What am I doing wrong and how should I fix this?
Finally, I've found the reason for such weird behavior: The callback is running on a thread which is separate from the UI thread.
In order to allow a fragment of code to do UI-related things you have to use dispatch_async() method. Here is my updated code with working navigation using mentioned method: