1
votes

Say there is an error in ViewController2, and I want to go back to ViewController1, the previous view controller and then display an alert. Right now if I put this in ViewController2

    @IBAction func testing(_ sender: Any) {
    navigationController?.popViewController(animated: true)
    Alert.alert(userTitle: "Error", userMessage: " ", userOptions: " ", in: LandingViewController() as UIViewController)

}

using this as the Alert class

    public class Alert {
    class func alert(userTitle: String?, userMessage: String, userOptions: String, in vc: UIViewController) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: userTitle, message: userMessage, preferredStyle: UIAlertControllerStyle.alert)
            alert.addAction(UIAlertAction(title: userOptions, style: UIAlertActionStyle.default, handler: nil))
            vc.present(alert, animated: true, completion: nil)
        }

    }

}

It will throw an error

So is there a way to do this?

1
What error is thrown? In line 3 of your code, you create a new instance of a view controller, rather than finding an existing one.Chris

1 Answers

6
votes

The problem is that LandingViewController() as UIViewController is not rendered in UiWindow

try this

guard let nav = navigationController, let top = nav.topViewController else {
    return
}

nav.popViewController(animated: true)
Alert.alert(userTitle: "Error", userMessage: " ", userOptions: " ", in: top)