Swift : self.window?.rootViewController 在 AppDelegate 中不起作用

Swift : self.window?.rootViewController doesn't work in AppDelegate

我想在用户按下推送通知时导航到某个屏幕。 但是,self.window?.rootViewController 一直给我错误,即 Thread 1: Swift runtime failure: force unwrapped a nil value.

现在我已经尝试使用 this solution。它确实起作用了;但是,它要求我将 SceneDelegate.swift 文件与其他文件一起删除,而我不想这样做。

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        print("userNotificationCenter didReceive")
        defer {
            completionHandler()
        }
        guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else {
            return
        }

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let destinationVC = storyboard.instantiateViewController(withIdentifier: "MyPage") as! PageViewController

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

        navigationController.pushViewController(destinationVC, animated: false)

        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }

当用户按下推送通知时,谁能告诉我另一种导航到特定位置的方法?提前谢谢你。

您应该改用 keyWindow。试试这个扩展:

extension UIApplication
{
    static func getKeyWindow() -> UIWindow? {
        return shared
            .connectedScenes
            .flatMap { ([=10=] as? UIWindowScene)?.windows ?? [] }
            .first { [=10=].isKeyWindow }
    }
}

然后:

let navigationController = UIApplication.getKeyWindow()?.rootViewController as! UINavigationController

navigationController.pushViewController(destinationVC, animated: false)

UNUserNotificationCenter.current().removeAllDeliveredNotifications()

你可以试试这个;

UIApplication.shared.keyWindow?.rootViewController

使用 keyWindow 而不是 window