簡體   English   中英

iOS推送通知點擊導致應用崩潰

[英]iOS push notification click causes app to crash

我的推送通知點擊有問題。 每次用戶單擊通知時,應用程序將崩潰,而不是將用戶重定向到指定頁面。

這部分代碼導致錯誤“無法將類型'appname.LaunchScreenController'的值強制轉換為'UINavigationController'”

let rootViewController = self.window!.rootViewController as! UINavigationController

並且此代碼將導致致命錯誤:解開Optional值時意外發現nil

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

提前致謝

RootViewController是UIViewController子類,而不是UINavigationController您必須處理null

改成

let rootViewController = self.window!.rootViewController

我將代碼更改為此並且現在可以正常工作

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)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM