Search code examples
iosswiftswift3

Pop to root view controller from modal


I am trying to pop to the root view controller using the following code:

self.navigationController!.popToRootViewController(animated: true)

This usually works, but I get an error when trying to use this code when the current view is a modal. How do I go about popping back to the root view controller in this situation?

Thanks in advance.


Solution

  • You can check that current controller is presented, if it is presented then dismiss it and the go to the rootViewController other wise go directly the rootViewController

    if self.presentingViewController != nil {
        self.dismiss(animated: false, completion: { 
           self.navigationController!.popToRootViewController(animated: true)
        })
    }
    else {
        self.navigationController!.popToRootViewController(animated: true)
    }