ios - AppDelegate 中的本地通知问题

标签 ios swift xcode uilocalnotification

我有一个闹钟应用程序。它有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)

非常感谢!

附言当应用程序处于前台或应用程序处于 VC1 时,是否可以在屏幕顶部发出带有 VC2 链接的通知?

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

最佳答案

替换这一行

(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")
}

关于ios - AppDelegate 中的本地通知问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42982763/

相关文章:

ios - 推送通知在 Firebase 4.0 中不起作用

iphone - 什么技术最适合将 iPhone 摄像机数据流式传输到计算机?

swift - 如何将变量的值设置为在日期选择器中选择的小时值

swift - 在多参数函数中解包可选

Xcode 4.5 虚假代码签名

ios - 在多个 Storyboard文件之间共享场景。 iPhone 与 iPad

ios - 为什么 Realm addOrUpdateObject 会导致属性设置为 nil?

xcode - Facebook 登录问题 -canOpenURL : failed for URL: "fbauth2:///" - error: "(null)"

javascript - 无法在用于 iOS UI 测试的密码文本字段中输入文本

objective-c - 在iPhone应用程序中执行核心图时出现错误:“-[UIView setHostedGraph:]:无法识别的选择器”