Swift: “Attempt to present UIAlertController whose view is not in the window hierarchy!”

风格不统一 提交于 2019-12-05 19:04:10

This line:

ViewController().present(alertView!, animated: true, completion: nil)

creates a new instance of ViewController and calls the present method on it. That won't work. You need to call it from a view controller that is itself presented. It looks like that code is inside ConsoleViewController, maybe you can just use self there.

try to present your UIAlertController in a DispatchQueue

DispatchQueue.main.async {

    let alert = UIAlertController(title: "Alert!", message: nil, preferredStyle: .alert)

    let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)

    alert.addAction(cancelAction)
    self.present(alert, animated: true, completion: nil)   
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!