I am having an issue with my push notification click. Everytime user clicks on the notifications, the app will crash instead of redirecting user to the specified page.
This part of the code is causing an error "Could not cast value of type 'appname.LaunchScreenController' to 'UINavigationController'" :
let rootViewController = self.window!.rootViewController as! UINavigationController
And this code will cause fatal error: unexpectedly found nil while unwrapping an Optional value :
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
//receive the notifications
NotificationCenter.default.post(name: Notification.Name(rawValue: "MyNotificationType"), object: nil, userInfo: userInfo)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NewsController") as! NewsViewController
let rootViewController = self.window!.rootViewController as! UINavigationController
rootViewController.pushViewController(vc, animated:true)
}
Thanks in advance
RootViewController is subclass of UIViewController
not a UINavigationController
You have to handle your null
values
change to
let rootViewController = self.window!.rootViewController
I change the code to this and it works just fine now
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
NotificationCenter.default.post(name: Notification.Name(rawValue: "MyNotificationType"), object: nil, userInfo: userInfo)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "NewsController") as! NewsViewController
let nav = UINavigationController()
nav.pushViewController(vc, animated: true)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.