iOS版.尝试在UIViewController上呈现UIAlertController,其视图不在窗口层次结构中

Igo*_*uan 9 uiviewcontroller ios swift

Swift 3,Xcode 8.1.我想显示UIAlertControllerUIViewController.

我有方法:

private static func rootViewController() -> UIViewController {
    // cheating, I know

    return UIApplication.shared.keyWindow!.rootViewController!
}

static func presentAlert(_ message: String) {
    let alertView = UIAlertController(title: "RxExample", message: message, preferredStyle: .alert)
    alertView.addAction(UIAlertAction(title: "OK", style: .cancel) { _ in })

    rootViewController().present(alertView, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到此课程的完整代码

我将方法presentAlert称为viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    DefaultWireframe.presentAlert("test")
    ...
}
Run Code Online (Sandbox Code Playgroud)

并得到警告:

警告:尝试在UIViewController上显示UIAlertController:0x7f904ac0d930:0x7f904ad08040,其视图不在窗口层次结构中!

如何避免警告并显示警报?

它在我尝试在初始ViewController中显示Alert时有效,但它在使用push segue与初始VC连接的另一个ViewController中不起作用.

小智 24

在viewDidLoad中,您的应用尚未向用户显示视图控制器,因此无法显示警报.尝试在viewDidAppear中执行该代码