'SwiftUI can't redirect on receiving push notifications

I'm developing in SwiftUI and I want to get a message when I get a push notification so I can navigate to a specific part of the app. After googling I can't get that info on the view side. I'm using scenes.

My AppDelegate

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
            

    func application(_ application: UIApplication,
                     configurationForConnecting connectingSceneSession: UISceneSession,
                     options: UIScene.ConnectionOptions) -> UISceneConfiguration {

        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        UNUserNotificationCenter.current().delegate = self
    }
}

extension SceneDelegate: UNUserNotificationCenterDelegate {
    
    // Foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
       
        // TODO: Refresh screen if already in right screen
        completionHandler([.banner, .sound])
    }
    
    // User tapped
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {

        switch response.actionIdentifier {
        case UNNotificationDismissActionIdentifier: // Notification was dismissed by user
            completionHandler()
        case UNNotificationDefaultActionIdentifier: // App was opened from notification
           
            // ----> This crashes. UIApplication.shared.delegate is an optional with some(SwiftUI.AppDelegate)
              let appDelegate = UIApplication.shared.delegate as! AppDelegate
              appDelegate.receivedPushNotification = true
            
            completionHandler()
        default:
            completionHandler()
        }
    }
}

The idea is then use AppDelegate as @EnvironmentObject in the view and check that value being changed. Thank you in advance for any help.



Solution 1:[1]

I ended up removing SceneDelegate entirely and use the UNUserNotificationCenterDelegate in the AppDelegate instead. Added a variable there where I set it and then read as an environmentObject.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lopes710