Filipe
Filipe

Reputation: 137

Swift 3: popToViewController not working

In my app I have three table view controllers and then potentially many UIViewControllers each of which has to lead back to the first table view controller if the user presses back at any point. I don't want the user to have to back through potentially hundreds of pages. This is what I amusing to determine if the user pressed the back button and it works the message is printed

override func viewWillDisappear(_ animated: Bool) {
    if !movingForward {
        print("moving back")
        let startvc = self.storyboard!.instantiateViewController(withIdentifier: "FirstTableViewController")
        _ = self.navigationController!.popToViewController(startvc, animated: true)
    }
}

I have searched and none of the solutions have worked so far.

Upvotes: 3

Views: 7522

Answers (3)

bshirley
bshirley

Reputation: 8356

If you are in a callback, particularly an async network callback, you may not be on the main thread. If that's you're problem, the solution is:

DispatchQueue.main.async {
    self.navigationController?.popToViewController(startvc, animated: true)
}

The system call viewWillDisappear() is always called on the main thread.

Upvotes: -1

Nirav D
Nirav D

Reputation: 72460

popToViewController not work in a way you are trying you are passing a complete new reference of FirstTableViewController instead of the one that is in the navigation stack. So you need to loop through the navigationController?.viewControllers and find the FirstTableViewController and then call popToViewController with that instance of FirstTableViewController.

for vc in (self.navigationController?.viewControllers ?? []) {
    if vc is FirstTableViewController {
        _ = self.navigationController?.popToViewController(vc, animated: true)
        break
    }
}

If you want to move to First Screen then you probably looking for popToRootViewController instead of popToViewController.

_ = self.navigationController?.popToRootViewController(animated: true)

Upvotes: 15

KKRocks
KKRocks

Reputation: 8322

Try this :

let allViewController: [UIViewController] = self.navigationController!.viewControllers as [UIViewController];

                        for aviewcontroller : UIViewController in allViewController
                        {
                            if aviewcontroller .isKindOfClass(YourDestinationViewControllerName)// change with your class
                            {
                             self.navigationController?.popToViewController(aviewcontroller, animated: true)
                            }
                        }

Upvotes: 1

Related Questions