How to redirect the user to a specific view after clicking on a push notification in SwiftUI iOS 15 / Xcode 13 (no Storyboard)?

Viewed 437

I have push notification on my app (works well) and I would like to redirect my users to my "Messages" view when they click on the notification, how to do that in SwiftUI (no Storyboard)?

I know that i have to implement the code in this function (in AppDelegate) :

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

}

My main view is a Tabview and "Messages" view is in it in a navigation View.

Thanks for your help!

1 Answers

So i think that we just have to modify these lines ...

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

// retrieve the root view controller (which is a tab bar controller)
guard let rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController else {
    return
}

let storyboard = UIStoryboard(name: "Main", bundle: nil)

// instantiate the view controller we want to show from storyboard
// root view controller is tab bar controller
// the selected tab is a navigation controller
// then we push the new view controller to it
if  let conversationVC = storyboard.instantiateViewController(withIdentifier: "ConversationViewController") as? ConversationViewController,
    let tabBarController = rootViewController as? UITabBarController,
    let navController = tabBarController.selectedViewController as? UINavigationController {

        // we can modify variable of the new view controller using notification data
        // (eg: title of notification)
        conversationVC.senderDisplayName = response.notification.request.content.title
        // you can access custom data of the push notification by using userInfo property
        // response.notification.request.content.userInfo
        navController.pushViewController(conversationVC, animated: true)
}

// tell the app that we have finished processing the user’s action / response
completionHandler()

}

So i think that we can change :

guard let rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController else { return }

to

    guard let rootViewController = UIApplication.shared.currentUIWindow()?.rootViewController else {
        return
    }

But for the rest I don't know how to make the changes

Related