Search code examples
iosswiftappdelegaterootviewuiscenedelegate

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


I want to open the "Menu View Controller", when a local notification is opened from the Notification Center. My problem is that I do not know how I can open a view controller from the AppDelegate. All solutions I found did not work, because it were for older Xcode versions before the SceneDelegate was introduced. This is the function in the AppDelegate where I want to call the view controller.

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

        completionHandler()

    }

I use a tab bar controller to navigate between some view controllers. I am not sure if that makes a difference. Here is how the important part of my storyboard looks. roo

I hope you can help me. Thank you!


Solution

  • You have 2 possible ways of doing this:

    1. Instantiate your tab bar controller via storyboard.

    Go to your storyboard and set a storyboard ID for your tab bar controller inside the identity inspector.

    Once you go that, you can instantiate your view controller like this:

    let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
    if let tabController = storyboard.instantiateViewController(withIdentifier: "tabControllerID") as? UITabController {
        tabController.selectedIndex = index
    }
    
    1. Or, you can access scene delegate from your AppDelegate and use window -> rootViewController to get access to your 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
            }
    
        }