【发布时间】:2019-07-18 09:14:08
【问题描述】:
我正在使用Firebase 开发实时聊天应用程序,所以一切对我来说都很好,但我根据通知类型直接重定向到viewcontroller,并且我被成功重定向但问题是当应用程序第一次启动时比我崩溃并出现如下错误
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
这是我的didReceiveRemoteNotification 代码
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let notificationType = userInfo["notification_type"] as! String //i am getting crash here
if notificationType == "news_notification"{
let rootViewController = self.window?.rootViewController as! UINavigationController
let storyboard = UIStoryboard(name: "Settings", bundle: nil)
let VC = storyboard.instantiateViewController(withIdentifier: "NewsDetailViewController") as! NewsDetailViewController
if let aps = userInfo["aps"] as? NSDictionary{
if let alert = aps["alert"] as? NSDictionary{
if let body = alert["body"] as? String{
print(body)
VC.name1 = body
}
if let title = alert["title"] as? String{
print(title)
VC.name = title
}
}
}
VC.vcValue = "1"
rootViewController.pushViewController(VC, animated: true)
}
}
如果我注释了这段代码,然后在登录后成功登录,我取消注释这段代码,它工作正常,但只是第一次启动我收到错误
【问题讨论】:
-
那么就守着回来?
guard let notificationType = userInfo["notification_type"] as? String else {return} -
听错了,别再这样解包了,你不能在任何地方使用
as! -
什么是键“notification_type”,为什么您认为“notification_type”应该始终存在?
-
@AndrewRomanov 是的,你是对的,但是如何检查“notification_type”是否可用
-
@Sh_Kh 发布了正确答案
标签: ios swift push-notification