Thomas Thomas - 13 days ago 12
Swift Question

Swift - Change root view controller and dismiss all view controllers

I have an application in which if I already have a user's

facebookUID
saved, I present them with the
MainViewController
and set it as the
rootViewController
, and if not, I present them with the
LoginViewController
as the
rootViewController
in my
AppDelegate.swift
file.

Inside the
MainViewController
, there is a
SettingsViewController
screen that I present modally. Inside that settings screen I have a logout button.

My question is, how can set the
rootViewController
as the
LoginViewController
, and dismiss all the other controllers in the stack when they click the logout button?

Answer

You do it, in essence, exactly the same way you do it in the app delegate. But you are not in the app delegate, so you have to get there in steps:

  1. From the UIApplication class you can get a reference to the shared application object.

  2. From there you can get the app's delegate.

  3. From there you can get the app delegate's window.

  4. Now you can set the window's rootViewController.

The view controller that was the root view controller will vanish in a puff of smoke, along with all its dependent view controllers.

(This, however, is not quite how I would do it. I would have a stable root view controller whose only job is to be custom parent view controller to either the LoginViewController or the MainViewController. I'm not fond of the idea of changing root view controller's in the middle of the app. Still, it's not illegal.)