user5513630 user5513630 - 2 years ago 151
Swift Question

how to call view controller with navigation controller

I have one view controller called login VC with navigation view controller.And i connect two button in my LoginVc.First button will navigate to signUp Screen as push segue.Second button will navigate to forgot password screen as push segue.

Now when user logged in and enter in to my app means.There is one button name called Log out.I have written the code functionality like, when user press log out button one uialert pop up will ask "Do You want to log out".If user press they will navigate to again login screen .

So after user pressed log out and if user came to login screen and if user press my two button [ i. e means forgot password screen, sign up screen button].Then i am getting crash.

Crash report :

Terminating app due to uncaught exception 'NSGenericException', reason: 'Push segues can only be used when the source controller is managed by an instance of UINavigationController.'

My log out button code :

@IBAction func LogoutButton(sender: AnyObject) {

NSUserDefaults.standardUserDefaults().setBool(false, forKey: "ISLOGGEDIN")


dispatch_async(dispatch_get_main_queue(), {

let alert = UIAlertController(title: "Logout Successful", message: "You have successfully logged out.", preferredStyle: UIAlertControllerStyle.Alert)

// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default){action -> Void in

let loginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as? LoginViewController

let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

appDelegate.window?.rootViewController = loginViewController


// show the alert
self.presentViewController(alert, animated: true, completion: nil)



I try adding this line :

let vc: UINavigationController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as! UINavigationController

But i am getting same problem.Now how can i re write my code in my log out button action method.To redirect to login screen with navigation bar.

Please help me out.Thanks!

Answer Source

You are setting the RootViewController to a ViewController but your application is NavigationViewController. Your RootViewController should be a NavigationController. So add your LoginViewController to NavigationViewController and set that rootViewController of window.

let loginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as? LoginViewController
let navigationController = UINavigationController(rootViewController: vc)
window.rootViewController = navigationController
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download