0

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!

Marcy
  • 4,611
  • 2
  • 34
  • 52
JPJerry5
  • 107
  • 10
  • Look up the accepted answer on the following thread: https://stackoverflow.com/questions/25325923/programmatically-switching-between-tabs-within-swift – rs7 Jun 01 '20 at 22:57
  • Thank you, but unfortunately does that not work for me. I only get the error value of type 'AppDelegate' has no member of 'window'. Only the last response is for iOS13. In that case I have to implement the solution in SceneDelegate, but I still do not know how to get it to the AppDelegate. – JPJerry5 Jun 01 '20 at 23:21

1 Answers1

1

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
        }

    }
rs7
  • 1,618
  • 1
  • 8
  • 16