Search code examples
iosswiftxcode7uisplitviewcontroller

How to reload the root view controller after logging out?


According to Apple, the split view should always be the root view controller throughout the life time of the app.

Anytime I log out of an account, the only way I was able to reload the detail view controller data was to make the log-in controller the root view controller if the user logged out, and then make the spit view the root view controller again.

This is just an example:

// if the user is not logged in
if FIRAuth.auth()?.currentUser?.uid == nil {
        window?.rootViewController = UINavigationController(rootViewController: LoginController())
    } else {
        // If the user is logged in, show the main controller
        window?.rootViewController = UINavigationController(rootViewController: MainController(collectionViewLayout: UICollectionViewFlowLayout()))
    }

Without doing what I did above: If I were to log out, the log-in view would present itself modally. If I were to sign in to a different account and then dismiss the login controller modally, the split view would still look the same from the last account. So is there a method or a technique for me to present the log in controller with animation that, upon re-login, the split view updates? I want to make sure I follow the guidelines.

(Note: the root of the detail view controller in the split view is a UICollectionViewController. I'm doing all of this programmatically.)


Solution

  • I normally have one rootViewController, that stays as a root forever. Its purpose is to hold and present login and mainController. This way you always have have a rootViewController, It gives dynamic of switching between presented controllers.

    I personally prefer to re allocate login controller and main controller before presentation, to be sure no data is left from the last logged in user.

    Example:
    
    class rooViewController: UIViewController {
    
        func presentedLogin() {
            self.loginController = LoginController()
            self.mainController.dismissViewControllerAnimated(true) { 
                self.presentViewController(self.loginController, animated: true, completion: nil)
            }
        }
    
        func presentMainApplication() {
            self.mainController = MainController()
            self.loginController.dismissViewControllerAnimated(true) {
                self.presentViewController(self.mainController, animated: true, completion: nil)
            }
        }
    }
    
    
    //App Delegate or any ether place of this application logic:
    
      if FIRAuth.auth()?.currentUser?.uid == nil {
                rootViewController.presentedLogin()
            } else {
                // If the user is logged in, show the main controller
                rootViewController.presentMainApplication()
            }