Swift – How to dismiss all of view controllers to go back to root

Try This :

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

it should dismiss all view controllers above the root view controller.

If that doesn’t work than you can manually do that by running a while loop like this.

func dismissViewControllers() {

    guard let vc = self.presentingViewController else { return }

    while (vc.presentingViewController != nil) {
        vc.dismiss(animated: true, completion: nil)
    }
}

It would dismiss all viewControllers until it has a presentingController.

Edit : if you want to dismiss/pop pushed ViewControllers you can use

self.navigationController?.popToRootViewController(animated: true)

Hope it helps.

Leave a Comment