【问题标题】:Swift : self.window?.rootViewController doesn't work in AppDelegateSwift:self.window?.rootViewController 在 AppDelegate 中不起作用
【发布时间】:2021-12-17 15:25:31
【问题描述】:

当用户按下推送通知时,我想导航到某个屏幕。 但是,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()
    }

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

【问题讨论】:

  • 使用这个UIApplication.shared.windows.first?.rootViewController
  • 不要使用 windows 甚至 keyWindow。如果你使用场景,你应该得到UIApplication.shared.connectedScenes.first?.delegate?.window
  • @RajaKishan 它有效。非常感谢。

标签: ios swift push-notification uinavigationcontroller uiscenedelegate


【解决方案1】:

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

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

然后:

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

navigationController.pushViewController(destinationVC, animated: false)

UNUserNotificationCenter.current().removeAllDeliveredNotifications()

【讨论】:

    【解决方案2】:

    你可以试试这个;

    UIApplication.shared.keyWindow?.rootViewController
    

    使用 keyWindow 代替窗口

    【讨论】:

      猜你喜欢
      • 2016-07-05
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      相关资源
      最近更新 更多