Search code examples
swiftstoryboardapple-push-notificationsappdelegateuiscenedelegate

instantiate view controller from fcm push notification


So for some reason, there is always an issue when instantiating from AppDelegate. I have a notification with a UNNotificationAction and I handle the action selection in the didReceiveResponse() method.

Here is the function:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
  
       // Print message ID.
       if let messageID = userInfo[gcmMessageIDKey] {
         print("Message ID: \(messageID)")
       }
    
   
    if response.actionIdentifier == "viewNewEvent" {
        let dashVC: UIViewController = storyboard.instantiateViewController(withIdentifier: Constants.StoryboardIDs.StudentEventDashboardStoryboardID) as! StudentSegmentedTableViewController
        let navDashVC = UINavigationController(rootViewController: dashVC)
        self.window?.rootViewController = navDashVC
        self.window?.makeKeyAndVisible()
        
    }

       print(userInfo)
    print("didReceiveResponse called")

    completionHandler()
}

The block of code in the if statement never runs when I select the action in the notification. At first, I was force unwrapping everything and I got an error saying the viewController was nil, now when I run and select the action in the notification, nothing happens.

How can the viewController be nil? I've faced something similar and decided to try it in the SceneDelegate instead, and it worked but there's so much bugs that I need to eventually fix. Am I better off using a UIScene and UIWindowScene in this situation than just UIWindow to try to to instantiate the right VC? Or is there a solution to this?


Solution

  • Ok so after a couple hours of research, I've realized that this cannot be done in AppDelegate anymore and I've now got to use SceneDelegate for anything to do with UIWindow and UIScene.