Dismiss all view controllers at once in Swift

There are flows in your app where you want to return to the very beginning of the application. It can be due to session expiry or end of flow in a linear activity like filling multipage forms or any other scenario. You want to come back to the beginning of the app. This can be achieved in two ways, depending on whether the view controllers are presented or pushed.

When the view controllers are pushed

When the view controllers are pushed into a navigation bar then you can easily pop to the first view controller by using

self.navigationController?.popToRootViewController(animated: true)

When the view controllers are presented

When the view controllers are presented you can dismiss all view controllers by calling dismiss on the rootviewcontroller as shown below

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

There are also cases where you would like to pop to a specific view controller this can also be achieved using the navigation controller’s viewcontrollers property. It returns all the pushed view controllers and we can pop to specific view controller either by giving index or checking type

NEED A JOB? NEED TO HIRE? NEED HELP?

Join group of Software Professionals

iOS DEVELOPER’S DEN