Swift 4 Attempt to present ViewController whose view is not in the window hierarchy

This issue happens due to your view hierarchy.

You need to find out what is your Current/Topmost view controller in view hierarchy and present your alert over it.

To find out topmost view controller use following code:

func getTopMostViewController() -> UIViewController? {
    var topMostViewController = UIApplication.shared.keyWindow?.rootViewController

    while let presentedViewController = topMostViewController?.presentedViewController {
        topMostViewController = presentedViewController
    }

    return topMostViewController
}

And present your alert over topmost view controller and use main thread to present an alert because closures may have working on another thread.

DispatchQueue.main.async { 
    getTopMostViewController()?.present(alertController, animated: true, completion: nil)
}

Please refer to this stack answer: Swift 3 Attempt to present whose view is not in the window hierarchy

Leave a Comment