Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13787

Swift - How to open specific view controller when push notification received?

I got stuck specific view controller is not move when I tap on push notification alert when application is not open stage totally.

Here is my code:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    /*

    fetch and add push notification data

     */
    goAnotherVC()
}

func goAnotherVC() {
    if (application.applicationState == UIApplicationState.active) {
        /* active stage is working */ 
    } else if (application.applicationState == UIApplicationState.inactive || application.applicationState == UIApplicationState.background) {
        if (type == "1" || type == "2") {
            let storyboard: UIStoryboard = UIStoryboard(name: "MyAppointments", bundle: nil)
            let apptVC = storyboard.instantiateViewController(withIdentifier: "NotificationDetailViewController") as! NotificationDetailViewController
            let navigationController = UINavigationController.init(rootViewController: apptVC)
            self.window?.rootViewController = navigationController
            self.window?.makeKeyAndVisible()
        } else if (type == "3") {
            let storyboard: UIStoryboard = UIStoryboard(name: "MyAppointments", bundle: nil)
            let apptVC = storyboard.instantiateViewController(withIdentifier: "NotificationDetailViewController") as! NotificationDetailViewController
            let navigationController = UINavigationController.init(rootViewController: apptVC)
            self.window?.rootViewController = navigationController
            self.window?.makeKeyAndVisible()
        } else if (type == "4") {
            let storyboard: UIStoryboard = UIStoryboard(name: "Enquiry", bundle: nil)
            let enqVC = storyboard.instantiateViewController(withIdentifier: "EnquiryDetailViewController") as! EnquiryDetailViewController
            let navigationController = UINavigationController.init(rootViewController: enqVC)
            self.window?.rootViewController = navigationController
            self.window?.makeKeyAndVisible()
        }
    }
}

I can get notification and tap to move specific VC when application is active. Please help me what I am missing.

Upvotes: 15

Views: 36090

Answers (3)

Debashish Das
Debashish Das

Reputation: 919

Swift 5, iOS 13 -

Since iOS 13 "window" is available in SceneDelegate. But the didReceiveNotification method is still present in AppDelegate.

So you have to first access the window from SceneDelegate

let window = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window

Now You can set the rootViewController property of the window

    window.rootViewController = viewControllerObject
    window.makeKeyAndVisible()

Upvotes: 1

Essam Fahmy
Essam Fahmy

Reputation: 2245

Swift 5

Simply, implement the following function which will be called when the user clicked on the notification.

In AppDelegate:

// This method is called when user clicked on the notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
{
    // Do whatever you want when the user tapped on a notification
    // If you are waiting for specific data from the notification 
    // (e.g., key: "target" and associated with "value"), 
    // you can capture it as follows then do the navigation:

    // You may print `userInfo` dictionary, to see all data received with the notification.
    let userInfo = response.notification.request.content.userInfo
    if let targetValue = userInfo["target"] as? String, targetValue == "value"
    {
        coordinateToSomeVC()
    }
    
    completionHandler()
}

private func coordinateToSomeVC()
{
    guard let window = UIApplication.shared.keyWindow else { return }

    let storyboard = UIStoryboard(name: "YourStoryboard", bundle: nil) 
    let yourVC = storyboard.instantiateViewController(identifier: "yourVCIdentifier")
    
    let navController = UINavigationController(rootViewController: yourVC)
    navController.modalPresentationStyle = .fullScreen

    // you can assign your vc directly or push it in navigation stack as follows:
    window.rootViewController = navController
    window.makeKeyAndVisible()
}

Note:

If you navigate to a specific controller based on the notification, you should care about how you will navigate back from this controller because there are no controllers in your stack right now. You must instantiate the controller you will back to. In my case, when the user clicked back, I instantiate the home controller and make it the app root again as the app will normally start.

Upvotes: 21

Joe
Joe

Reputation: 4074

When you app is in closed state you should check for launch option in

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { }

and call your API.

Example:

if let option = launchOptions {
  let info = option[UIApplicationLaunchOptionsKey.remoteNotification]
  if (info != nil) {
    goAnotherVC()
  }
}

Upvotes: 13

Related Questions