AlertController is not in the window hierarchy

If you’re instancing your UIAlertController from a modal controller, you need to do it in viewDidAppear, not in viewDidLoad or you’ll get an error.

Here’s my code (Swift 4):

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let alertController = UIAlertController(title: "Foo", message: "Bar", preferredStyle: .alert)

    alertController.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
    present(alertController, animated: true, completion: nil)
}

Leave a Comment