I have an app which is a single view application. I have a navigation controller linked up to all child controllers from the root view controller.
In each child controller, I have a logout button. I'm wondering if I can have a single function I can call which will dismiss all the controllers which have been open along along the way, no matter which controller was currently open when the user presses logout?
My basic start:
func tryLogout(){ self.dismissViewControllerAnimated(true, completion: nil) let navigationController = UINavigationController(rootViewController: UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("LoginViewController") ) self.presentViewController(navigationController, animated: true, completion: nil) }
I am looking for the most memory efficient way of carrying out this task. I will put my logout function in a separate utils file, but then I can't use self. And I still have the issue of knowing which controllers to dismiss dynamically.
Update Pop to root view controller has been suggested. So my attempt is something like:
func tryLogout(ViewController : UIViewController){ print("do something") dispatch_async(dispatch_get_main_queue(), { ViewController.navigationController?.popToRootViewControllerAnimated(true) return }) }
Would this be the best way to achieve what I'm after?
Use unwind segue instead of using RootViewController. Using unwind you can go back to any ViewController. DismissViewController always send the controller out from NavigationController.
According to the View Controller Programming guide for iPhone OS, this is incorrect when it comes to dismissing modal view controllers you should use delegation. So before presenting your modal view make yourself the delegate and then call the delegate from the modal view controller to dismiss.
You can call :
self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)
Should dismiss all view controllers above the root view controller.
Updated answer for Swift 4 and swift 5
UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: true, completion: nil)
and when you use navigationController
self.navigationController?.popToRootViewController(animated: true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With