'How to dismiss and pop up a view controller in single click

I have 3 view controllers In the first view controller (ie. MydownloadViewController) i am using this to push to the another view controller.

  let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ImagePreviewViewController") as? ImagePreviewViewController
self.navigationController?.pushViewController(vc!, animated: true)

and from the image preview controller

 let vc = self.storyboard?.instantiateViewController(withIdentifier: "DeletePopupViewController") as! DeletePopupViewController
 self.present(vc, animated: false, completion: nil)

and from the delete view controller I want to back in my download view controller for this i am doing this -:

 self.dismiss(animated: true, completion:  {
                if let  destinationVC =  presentingVC.navigationController?.viewControllers.filter({$0 is MyDownloadsViewController}).first {
                    presentingVC.navigationController?.popToViewController(destinationVC, animated: false)
                            }

               })

But nothing happens what is wrong with this code.



Solution 1:[1]

When your popup dismisses the presenting controller instance would be nil. You may need to hold the reference prior. You may need to do something like the one below.

let presentingController = self.presentingViewController
self.dismiss(animated: true) {
    if let navigationController = presentingController as? UINavigationController,
       let myDownloadsViewController = navigationController.viewControllers.first(
           where: { viewController in
               viewController is MyDownloadsViewController
           }
       ) {
       navigationController.popToViewController(myDownloadsViewController, animated: true)
    }
}

Solution 2:[2]

Try this:

let viewControllers: [UIViewController] = self.navigationController?.viewControllers ?? []
                for viewController in viewControllers {
                    if viewController == MyDownloadsViewController() {
                        self.navigationController?.popToViewController(viewController, animated: true)
                    }
                }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Subramanian Mariappan
Solution 2 Dinesh