0

I want to popViewController after I dismiss a modalVC. However my code is not working. What is wrong?

func showMessage(withTitle title: String, message: String) {

        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)

        let alertAction = UIAlertAction(title: "ok", style: .default) { (_) in
            self.dismiss(animated: true) {
                self.navigationController?.popViewController(animated: true)
            }
        }
        
        alert.addAction(alertAction)
        
        present(alert, animated: true, completion: nil)
    }

I have also tried this:

  let controller = ViewController()             
controller?.popViewController(animated: true)
JuFa512
  • 119
  • 7
  • Shouldn´t this be `alert.dismiss(....`? – burnsi Jun 22 '22 at 12:47
  • You should use a delegate – Keshu R. Jun 22 '22 at 12:49
  • Check if your current `view controller` is pushed by `navigationController?.pushViewController`. I tested it in a controller that has `navigationController` and it worked fine. Try printing `navigationController?.viewControllers` to see the current state. – tanmoy Jun 22 '22 at 12:49
  • "nil" is what I get when printing this .. – JuFa512 Jun 22 '22 at 14:01
  • This means that you don't have a `UINavigationController` to work with. You have to wrap the VC in the navigation controller for it to be able to use it. – Alistra Jun 24 '22 at 13:59

1 Answers1

0

I created two viewcontrollers vc1 and vc2. vc1 has a navigation controller and vc2 is pushed on top of vc1 is the navigation stack. In vc2 the alert is shown and on tap of ok button vc2 is popped and removed from navigation stack. Works fine for me. Code for vc1:

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
  self.navigationController?.pushViewController(storyboard?.instantiateViewController(withIdentifier: "SecViewController") as? SecViewController ?? SecViewController(), animated: true)
}
}

Code for vc2:

class SecViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    showMessage(withTitle: "title", message: "Message")
}


func showMessage(withTitle title: String, message: String) {
    
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    
    let alertAction = UIAlertAction(title: "ok", style: .default) { (_) in
        self.dismiss(animated: true) {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    alert.addAction(alertAction)
    
    present(alert, animated: true, completion: nil)
}
Deepa Bhat
  • 174
  • 1
  • 10