【问题标题】:Swift: Show UIAlertController in didReceiveLocalNotification methodSwift:在 didReceiveLocalNotification 方法中显示 UIAlertController
【发布时间】:2016-02-27 07:25:12
【问题描述】:

我想在应用程序运行时触发通知时显示警报,这是我用于本地通知的tutorial。在教程中,它使用UIAlertView 来显示警报并且有效,代码如下:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    // Point for handling the local notification when the app is open.
    // Showing reminder details in an alertview
    UIAlertView(title: notification.alertTitle, message: notification.alertBody, delegate: nil, cancelButtonTitle: "OK").show()
}

但它警告说 UIAlertView 在 iOS 9 中已被弃用,所以我使用了UIAlertController,但是当我运行它时它会发出警告:

Attempt to present <UIAlertController: 0x7c322a00> on <xxx> whose view is not in the window hierarchy!

这是我的didReceiveLocalNotification 方法:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    let alert = UIAlertController(title: "", message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in
    }))

    self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}

如何在didReceiveLocalNotification 方法中显示 UIAlertController?我也试过了:

 let activeViewCont = application.windows[0].rootViewController?.presentedViewController
 activeViewCont!.presentViewController(alert, animated: true, completion: nil)

【问题讨论】:

  • self.window.rootViewController 这是您项目中的导航控制器吗?
  • @Nishant 不,我没有在我的项目中使用导航控制器。 self.window.rootViewController 返回我的 SplashScreen,我在其中创建了自己的启动画面,它会在应用程序第一次打开时下载数据。但我需要获取当前显示的视图控制器

标签: swift2 uialertview uialertcontroller localnotification


【解决方案1】:

试试这个:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {

    var topController : UIViewController = (application.keyWindow?.rootViewController)!

    while ((topController.presentedViewController) != nil) {

        topController = topController.presentedViewController!
    }

    let alert = UIAlertController(title: "", message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in}))

    topController.presentViewController(alert, animated: true, completion: nil)

})

希望对你有帮助。

【讨论】:

  • 我之前也试过这个,也没有用。它给出了同样的错误:Warning: Attempt to present &lt;UIAlertController&gt; on &lt;MyProject.SplashScreenViewController&gt; whose view is not in the window hierarchy!
  • 我想我需要找到当前显示的视图控制器,但我不知道如何,例如,当我收到该警告时,应用程序没有显示启动画面,它正在显示另一个视图控制器
  • 感谢您提供的链接中的解决方案解决了我的问题
  • @kakajan:太好了。我已将代码修改为正确答案。
  • 感谢您的帮助,我接受并赞成您的回答;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多