This extension will allow you to quickly change the root view controller in an iOS application, very useful for handling sessions.

extension UIViewController {
    
    func becomeRootViewController(animated: Bool, completion: (() -> Void)? = nil) {
        guard let window = UIApplication.shared.keyWindow else {
            return
        }
        if animated {
            UIView.transition(with: window, duration: 0.5, options: .transitionCrossDissolve, animations: {
                let previousValue = UIView.areAnimationsEnabled
                UIView.setAnimationsEnabled(false)
                window.rootViewController = self
                UIView.setAnimationsEnabled(previousValue)
            }) { (finished) in
                completion?()
            }
        } else {
            window.rootViewController = self
        }
    }
}

How to use:

let myViewController = MyViewController()
myViewController.becomeRootViewController(animated: true)

Optionally you can use the completion block.