JuFa512
JuFa512

Reputation: 159

popViewController after dismiss Modal VC Swift

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)

Upvotes: 0

Views: 105

Answers (1)

Deepa Bhat
Deepa Bhat

Reputation: 224

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)
}

Upvotes: 0

Related Questions