Thom Thom -4 years ago 85
iOS Question

Return control to my root controller

My first full swift 3 app.

I have a ViewController called RootViewController. I have a MainViewController and a LoginViewController.

When I start RootViewController, I check for login credentials in my

viewDidLoad()
. If there are none, I execute the following code to show my Login page:

if loginViewController == nil {
loginViewController = storyboard?.instantiateViewController(withIdentifier: RootViewController.LOGIN) as! LoginViewController!
}

if currentViewController != nil {
currentViewController!.willMove(toParentViewController: nil)
currentViewController.view.removeFromSuperview()
currentViewController!.removeFromParentViewController()
}

if loginViewController != nil {
loginViewController?.view.frame = view.frame
self.addChildViewController(loginViewController!)
self.view.insertSubview(loginViewController!.view, at: 0)
loginViewController!.didMove(toParentViewController: self)
}

currentViewController = loginViewController


Now my question is this. In my LoginViewController, the user has successfully logged in. How do I switch control back to my root view controller so that it will switch to my MainViewController?

My book doesn't have an example like this and I couldn't think how to search that didn't return a thousand bogies!

Answer Source

I use the following in AppDelegate:

func changeRootViewControllerToMyVC() {
        let storyboard = self.window?.rootViewController?.storyboard
        let desiredViewController = storyboard?.instantiateViewController(withIdentifier: "myViewController") as? myViewController;

        if let win = self.window{
            UIView.transition(with: win, duration: 0.3, options: UIViewAnimationOptions.transitionFlipFromLeft, animations: {
                win.rootViewController = desiredViewController
            }, completion: nil)
        }

    }

And I call it like this:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.changeRootViewControllerToMyVC()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download