尝试在UINavigationController上呈现UIAlertController,其视图不在窗口层次结构中

问题描述 投票:0回答:1

我正在尝试在AppDelegate中创建一个UIAlertController来处理我的前台本地通知。我的代码看起来像这样:

func application(application: UIApplication, didReceiveLocalNotificationnotification: UILocalNotification) {
    let state: UIApplicationState = application.applicationState
    if state == .Active {
        let alert: UIAlertController = UIAlertController(title: "test", message: "test", preferredStyle: UIAlertControllerStyle.Alert)
        self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)

    }
}

但后来我得到了这个错误:Attempt to present UIAlertController on UINavigationController whose view is not in the window hierarchy

我已经找到了可能的解决方案,但它们对我不起作用(dispatch_async,创建一个func)。我认为它与部件'rootviewcontroller'有关,但我不知道如何修复它。这可以修复还是在前台处理本地通知的另一种方法?

ios swift appdelegate uialertcontroller
1个回答
2
投票

因此,有几个原因可能导致此错误。我猜想你的根视图控制器还没有被显示,或者你的根视图控制器就像UINavigationController,它不应该呈现视图。

如果是后者,那么只需从顶视图控制器显示就可以轻松修复。所以这样的事情可能是:

(self.window?.rootViewController as? UINavigationController)?.topViewController.presentViewController(alert, animated: true, completion: nil)

在执行这项工作时,你真的应该远离dispatch_async,因为首先调度到除主线程之外的任何东西都会让你进入一个巨大的痛苦世界(UI操作只能在主线程上执行)并调度到结束时主队列是一个糟糕的解决方案(如果它可以工作)。

© www.soinside.com 2019 - 2024. All rights reserved.