简体   繁体   中英

App crashes after push notification is tapped when app is killed

I am attempting to launch a specific viewController in my CustomTabBarController after receiving remote notifications. But somehow, the app always crashes when the app is killed.

Meaning to say, kill the app -> received push notifications -> tap the notifications -> app launches and crashed. This also happens when I tap the notification from the lockscreen.

I am able to execute when the app is in the background, but not when the app is killed. My code so far:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    ...

    if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
        guard let rootViewController = self.window?.rootViewController as? CustomTabBarController else {
            return true
        }
        rootViewController.selectedIndex = 1

    }

    return true
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    if application.applicationState == .background || application.applicationState == .inactive {

        guard let rootViewController = self.window?.rootViewController as? CustomTabBarController else {
            return
        }
        rootViewController.selectedIndex = 1
    }        
}

I've followed this post to check the launchOptions, but it still crash. Can anyone advice pls?

Comment these 2 lines

// window = UIWindow(frame: UIScreen.main.bounds)
// window?.makeKeyAndVisible()

as overriding the window property destroys the initialization from storyboard (makes rootVC nil) and before return true window must have one

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM