79

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?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
user2363025
  • 6,365
  • 19
  • 48
  • 89
  • You might just want to reinitialize your app's `UIWindow`'s `rootViewController` property. That will remove your entire view hierarchy (assuming you're not using other windows, which is rare). – Aaron Brager Nov 04 '15 at 11:44
  • Are you presenting controllers or just pushing onto the nav stack? Where is the logout button? Can you just pop to root? What other clean up do you need to do? – Wain Nov 04 '15 at 11:44
  • @Wain I have my controller linked up with segue identifiers in certain cases and I am presentingViewControllers with the defined identifier. Then there are some cases where I'm just doing basic segues i.e. a button's action, a table row's click event. The logout button is added to the nav bar as a left bar button item. No other clean up really. Reset a few Global Prefs just – user2363025 Nov 04 '15 at 11:51
  • @Aaron Brager sorry if this is a silly question, but what do you mean exactly about using other windows? – user2363025 Nov 04 '15 at 11:52
  • @user2363025 Very rarely an iOS app will have multiple UIWindows. You would know if you were making and managing them. – Aaron Brager Nov 04 '15 at 12:07

11 Answers11

219

You can call :

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

Should dismiss all view controllers above the root view controller.

Krunal Nagvadia
  • 1,083
  • 2
  • 12
  • 33
Liam
  • 2,659
  • 1
  • 14
  • 16
  • Give this a go, let me know how it goes :), also assuming that self is the view controller that you are calling logout from. If it is called from somewhere else, you would need to pass the controller and replace self with the controller you would be calling logout from. – Liam Nov 04 '15 at 12:09
  • @Zorayr just change `false` to `true` for dismissAnimation, it should work: `self.view.window!.rootViewController?.dismissViewControllerAnimated(true, completion: nil)` – oyalhi Apr 19 '17 at 09:39
  • @Liam `self.view.window!.rootViewController?.dismissViewControllerAnimated(false, completion: nil) let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("LogIn") as UIViewController self.appDelegate.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.appDelegate.window?.rootViewController = initialViewControlleripad self.appDelegate.window?.makeKeyAndVisible()` This is my code – Coder Aug 03 '17 at 11:52
  • 1
    Suppose tested my app 5 times in that 3 times 'deinit {}' method is called sometime not. What is wrong with this ? And background my 'NSTimer' logic is working – Coder Aug 03 '17 at 11:55
  • 3
    Swift 3.0 syntax is `self.view.window!.rootViewController?.dismiss(animated: false, completion: nil)` – Pinwheeler Aug 07 '18 at 17:53
49

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)
Bijender Singh Shekhawat
  • 3,934
  • 2
  • 30
  • 36
38

Works for Swift 4 and Swift 5

To dismiss any unwanted residue Modal ViewControllers, I used this and worked well without retaining any navigation stack references.

UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)

self.view.window! did crash for my case possibly because its a Modal screen and had lost the reference to the window.

Naishta
  • 11,885
  • 4
  • 72
  • 54
8

Swift3

navigationController?.popToRootViewControllerAnimated(true)
markhorrocks
  • 1,199
  • 19
  • 82
  • 151
  • 1
    this will close all pushed view controllers at one, good answer – MGY Oct 24 '17 at 08:24
  • 2
    This is a good answer, and doesn't need to be **explained** further. – Alec O May 11 '18 at 14:26
  • This doesn't work for the presented controllers, and only work for the controller that are being pushed in the stack. The solution is to find the presented view controller and dismiss it – Swornim Shah Aug 27 '23 at 16:09
6

Take a look at how unwind segues work. Its super simple, and lets you dismiss/pop to a certain viewcontroller in the heirarchy, even if it consists of a complex navigation (nested pushed and or presented view controllers), without much code.

Here's a very good answer (by smilebot) that shows how to use unwind segues to solve your problem https://stackoverflow.com/a/27463286/503527

Community
  • 1
  • 1
Nitin Alabur
  • 5,812
  • 1
  • 34
  • 52
6

To dismiss all modal Views.

Swift 5


view.window?.rootViewController?.dismiss(animated: true, completion: nil)

hectorsvill
  • 681
  • 8
  • 7
1

If you have a customed UITabbarController, then try dismiss top viewController in UITabbarController by:

class MainTabBarController: UITabBarController {

    func aFuncLikeLogout() {

        self.presentedViewController?.dismiss(animated: false, completion: nil)

        //......
    }

}
Yun CHEN
  • 6,450
  • 3
  • 30
  • 33
1

If you have access to Navigation Controller, you can try something like this. Other solutions didn't work for me.

func popAndDismissAllControllers(animated: Bool) {
    var presentedController = navigationController?.presentedViewController

    while presentedController != nil {
        presentedController?.dismiss(animated: animated)
        presentedController = presentedController?.presentedViewController
    }

    navigationController?.popToRootViewController(animated: animated)
}
Dan Dolog
  • 241
  • 3
  • 3
0

works for Swift 3.0 +

self.view.window!.rootViewController?.dismiss(animated: true, completion: nil)
Vega
  • 27,856
  • 27
  • 95
  • 103
0

I have figured out a generic function to dismiss all presented controllers using the completion block.

extension UIWindow {
    static func keyWindow() -> UIWindow? {
        UIApplication.shared.windows.filter({ $0.isKeyWindow }).first
    }
}

func getVisibleViewController(_ rootViewController: UIViewController?) -> UIViewController? {
    
    var rootVC = rootViewController
    if rootVC == nil {
        rootVC = UIWindow.keyWindow()?.rootViewController
    }
    
    var presented = rootVC?.presentedViewController
    if rootVC?.presentedViewController == nil {
        if let isTab = rootVC?.isKind(of: UITabBarController.self), let isNav = rootVC?.isKind(of: UINavigationController.self) {
            if !isTab && !isNav {
                return rootVC
            }
            presented = rootVC
        } else {
            return rootVC
        }
    }
    
    if let presented = presented {
        if presented.isKind(of: UINavigationController.self) {
            if let navigationController = presented as? UINavigationController {
                return navigationController.viewControllers.last!
            }
        }
        
        if presented.isKind(of: UITabBarController.self) {
            if let tabBarController = presented as? UITabBarController {
                if let navigationController = tabBarController.selectedViewController! as? UINavigationController {
                    return navigationController.viewControllers.last!
                } else {
                    return tabBarController.selectedViewController!
                }
            }
        }
        
        return getVisibleViewController(presented)
    }
    return nil
}

func dismissedAllAlert(completion: (() -> Void)? = nil) {

    if let alert = UIViewController.getVisibleViewController(nil) {

    // If you want to dismiss a specific kind of presented controller then
    // comment upper line and uncomment below one

    // if let alert = UIViewController.getVisibleViewController(nil) as? UIAlertController {

        alert.dismiss(animated: true) {
            self.dismissedAllAlert(completion: completion)
        }

    } else {
        completion?()
    }

}

Note: You call anywhere in code at any class

Use:-

dismissedAllAlert()    // For dismiss all presented controller

dismissedAllAlert {    // For dismiss all presented controller with completion block
    // your code
}
-1

Swift Used this to jump directly on your ROOT Navigation controller.

self.navigationController?.popToRootViewController(animated: true)

Rahul Panzade
  • 1,302
  • 15
  • 12
  • 1
    popToRoot... doesnt dismiss presented controllers as they aren't added to navigation stack. – void Apr 08 '19 at 14:02