Tim Dietrich

Custom Software Developer

Home Services Portfolio Blog About Contact Newsletter

Swift: "Attempt to present UIAlertController on ViewController whose view is not in the window hierarchy!"

Last week, I wrote about a warning that was issued when my app would segue to a view controller and display a UIAlertController programmatically.

The warning read, "Presenting view controllers on detached view controllers is discouraged…" The problem was that I was presenting the UIAlertController in the view's viewDidLoad method, and while the view had loaded at that point, it wasn't actually displayed. The fix was to move the presentation of the UIAlertController to the viewDidAppear method.

I ran into a similar issue this morning. This time, however, I was trying to present a UIAlertController in the app's initial view controller, and the warning was slightly different.

Let's start with the alert that was issued. It read:

Warning: Attempt to present <UIAlertController: 0x7b196400> on <AlertViewTesting.ViewController: 0x7a9800f0> whose view is not in the window hierarchy!

The code looked like this:


override func viewDidLoad() {
	super.viewDidLoad()
	
	// Create a UIAlertController object.
	let alertController = UIAlertController(title: "Hello!", message: "Hello, world!",
		preferredStyle: UIAlertControllerStyle.Alert)
	
	// Display the alert.
	presentViewController(alertController, animated: true, completion: nil)
   
}

While the alert is different, its cause is the same: I was trying to display the alert in the root controller's viewDidLoad method. The root view had loaded, but it wasn't actually displayed yet. Or, as the warning states, the view was "not in the window hierarchy."

Again, the solution for this was simple: I moved the presentation of the alert to the viewDidAppear method.


override func viewDidAppear(animated: Bool) {
    
    // Create a UIAlertController object.
    let alertController = UIAlertController(title: "Hello!", message: "Hello, world!",
        preferredStyle: UIAlertControllerStyle.Alert)
    
    // Display the alert.
    presentViewController(alertController, animated: true, completion: nil)
    
}