繁体   English   中英

在AppDelegate中遇到本地通知问题

[英]Trouble with local notification in AppDelegate

我有一个闹钟应用程序。 它有2个VC。 VC1是与VC2链接的菜单VC。 在VC2中有闹钟的设置。 我收到本地通知时遇到了麻烦。

例如,如果我在VC2上设置闹钟然后我移动到VC1然后转到主屏幕我将在屏幕顶部收到通知。 点击通知后,我将移至VC1,我将收到一条消息。 但我会收到错误'无法将类型'MyApp.VC1'(0x10ee97730)的值转换为'MyApp.VC2'(0x10ee96bd0)'。 如果我在VC2上设置闹钟,那么我移动到主屏幕我将在屏幕顶部收到通知。 点击通知后我会转到VC2,我会收到一条消息,一切都会好的。

其他问题是在VC2上设置闹钟并移动到VC1而不移动到主屏幕。 什么时候我会来我的应用程序只是崩溃相同的错误'无法将类型'MyApp.VC1'(0x10ee97730)的值转换为'MyApp.VC2'(0x10ee96bd0)'

    func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
    let storageController = UIAlertController(title: "Alarm", message: nil, preferredStyle: .alert)
    var soundName: String = ""
    var index: Int = -1
    if let userInfo = notification.userInfo {
        soundName = userInfo["soundName"] as! String
        index = userInfo["index"] as! Int
    }

    playSound(soundName)

    let stopOption = UIAlertAction(title: "OK", style: .default) {
        (action:UIAlertAction)->Void in self.audioPlayer?.stop()
        let mainVC = self.window?.visibleViewController as! MainAlarmViewController


    storageController.addAction(stopOption)
    (self.window?.visibleViewController as! MainAlarmViewController).present(storageController, animated: true, completion: nil)

}

有人知道怎么解决吗?

当我收到错误时,我看到这一行的亮点:

(self.window?.visibleViewController as! MainAlarmViewController).present(storageController, animated: true, completion: nil)

非常感谢!

PS当前景中的应用程序或VC1中的应用程序时,也许可以在屏幕顶部发出通知,其中包含指向VC2的链接?

有时我也会收到一条消息“警告:尝试显示其视图不在窗口层次结构中!”

替换此行

(self.window?.visibleViewController as! MainAlarmViewController).present(storageController, animated: true, completion: nil)

使用以下代码

if let viewController = self.window?.visibleViewController {

       if viewController is MainAlarmViewController {
         // view controller is MainAlarmViewController
       } else {
         // view controller is not MainAlarmViewController
       }

       viewController.present(storageController, animated: true, completion: nil)
} else {
   print("Something wrong. Window can't provide visible view controller")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM