4

The issue in most questions similar to this one is that present is called before viewDidAppear. That is not the reason here.

This app does not use Storyboards of NIBs, and all operations are programmatic.

The rootViewController of the window of the app is a UISplitViewController. The view controllers of the split view are set to an array of two UINavigationControllers. A child view controller then modally presents a view controller. The problem is that UIAlertControllers presented from the app delegate won't show while a view controller is being modally presented. It works otherwise.

How I try to present:

window?.rootViewController?.present(alert, animated: true, completion: nil)

I get this error:

Attempt to present UIAlertController on UISplitViewController whose view is not in the window hierarchy
ahyattdev
  • 529
  • 1
  • 6
  • 18

1 Answers1

3

To solve this, I put this function in my app delegate.

// Utility function to avoid:
// Warning: Attempt to present * on * whose view is not in the window hierarchy!
func showAlertGlobally(_ alert: UIAlertController) {
    let alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.windowLevel = UIWindowLevelAlert
    alertWindow.rootViewController = UIViewController()
    alertWindow.makeKeyAndVisible()
    alertWindow.rootViewController?.present(alert, animated: true, completion: nil)
}
ahyattdev
  • 529
  • 1
  • 6
  • 18
  • 1
    A quite similar solution was proposed here: http://stackoverflow.com/a/34487871/1187415, for Swift 3 here: http://stackoverflow.com/a/40401936/1187415. – Martin R Dec 25 '16 at 17:31