1

I have 3 View Controllers: 1) LoginViewController. 2) MainViewController. 3) LogoutViewController.

I am using NSUserDefaults to store the username when he login from LoginViewController.

Then in the AppDelegate I use this method:

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let UserData = NSUserDefaults.standardUserDefaults()
    if (UserData.stringForKey("Username") != nil) {
        let initialViewController = storyboard.instantiateViewControllerWithIdentifier("MainViewController") as! MainViewController
        self.window?.rootViewController = initialViewController
    } else {
        let initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
        self.window?.rootViewController = initialViewController
    }

So, When there is Username stored in the NSUserDefaults, the app jump to Main View Controller and skip the first at App launch.

in the LogoutViewController I used unwind segue to LoginViewController, meaning that I have a logout button and I used unwind segue to go to the LoginViewController. That works fine when the app starts from LoginViewController but not from MainViewController.

However, I want the to go to LoginViewController when Logout Button Pressed whether it starts from LoginViewController or MainViewController and release all other ViewControllers from memory. How can it be?

FamousMaxy
  • 686
  • 5
  • 21

2 Answers2

1

You need to set the LoginViewController as rootViewController on logout instead of unwinding the segue.

let initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
UIApplication.sharedApplication().keyWindow?.rootViewController = initialViewController
Fahad Azeem
  • 541
  • 7
  • 14
  • Do we need to dismiss the other viewControllers on the stack? I'm worried that simply replacing the rootViewController will cause a memory leak by allowing the other viewControllers to exist – Vivian Apr 19 '18 at 04:52
  • 1
    No you don't need to dismiss other viewControllers. Setting RootViewController will reset the stack. – Fahad Azeem Apr 20 '18 at 07:56
0

In your case LoginViewController as root view is called first when app is launched. So when you log-out, you should pop to root view controller

brianha289
  • 338
  • 1
  • 8