如何从应用程序委托中打开视图控制器?

How do I open a view controller from the app delegate?

我想在从通知中心打开本地通知时打开 "Menu View Controller"。我的问题是我不知道如何从 AppDelegate 打开视图控制器。我找到的所有解决方案都不起作用,因为它适用于引入 SceneDelegate 之前的旧 Xcode 版本。这是我要调用视图控制器的 AppDelegate 中的函数。

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // missing code to open menu view controller

        completionHandler()

    }

我使用标签栏控制器在一些视图控制器之间导航。我不确定这是否有所作为。 这是我故事板的重要部分的外观。

希望你能帮助我。谢谢!

您有两种可能的方法:

1.通过故事板实例化您的标签栏控制器。

转到您的情节提要并在身份检查器中为标签栏控制器设置情节提要 ID。

完成后,您可以像这样实例化您的视图控制器:

let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
if let tabController = storyboard.instantiateViewController(withIdentifier: "tabControllerID") as? UITabController {
    tabController.selectedIndex = index
}
  1. 或者,您可以从您的 AppDelegate 访问场景委托并使用 window -> rootViewController 来访问您的 tabController:
    let scene = UIApplication.shared.connectedScenes.first
    if let sceneDelegate = scene?.delegate as? SceneDelegate {  
        if let tabController = sceneDelegate.window?.rootViewController as? UITabBarController {
              tabController.selectedIndex = index
        }

    }