Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

single function to dismiss all open view controllers

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?

like image 837
user2363025 Avatar asked Nov 04 '15 11:11

user2363025


People also ask

How do I dismiss a specific view controller in Swift?

Use unwind segue instead of using RootViewController. Using unwind you can go back to any ViewController. DismissViewController always send the controller out from NavigationController.

How do you dismiss a modal view controller?

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.


2 Answers

You can call :

self.view.window!.rootViewController?.dismiss(animated: false, completion: nil) 

Should dismiss all view controllers above the root view controller.

like image 139
Liam Avatar answered Sep 23 '22 17:09

Liam


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) 
like image 29
Bijender Singh Shekhawat Avatar answered Sep 20 '22 17:09

Bijender Singh Shekhawat