首页 > 解决方案 > 应用程序被杀死时点击推送通知后应用程序崩溃

问题描述

我正在尝试在收到远程通知后在我的 CustomTabBarController 中启动特定的 viewController。但不知何故,当应用程序被杀死时,应用程序总是崩溃。

意思是说,杀死应用程序->收到推送通知->点击通知->应用程序启动并崩溃。当我从锁屏点击通知时也会发生这种情况。

我可以在应用程序处于后台时执行,但不能在应用程序被终止时执行。到目前为止我的代码:

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

我已经按照这篇文章检查了launchOptions,但它仍然崩溃。接下来我可以尝试什么?

标签: iosswift

解决方案


评论这两行

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

因为覆盖窗口属性会破坏情节提要的初始化(使 rootVC 为零)并且在return true窗口必须有一个之前


推荐阅读