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