How can I open a specific view on notification tap in SwiftUI?

Viewed 243

I am trying to send a user to a DetailView once the notification is tapped. I've followed multiple instructions such as this one. However, when I test it out, tapping on the notification still brings me to the wrong view (the settingsView).

In App Delegate, I currently have this setup (for updated code scroll below):

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        registerBackgroundTasks()
        FirebaseApp.configure()
        UNUserNotificationCenter.current().delegate = self
    
        
                return true
    }

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

        if response.actionIdentifier == "open" {
                NotificationCenter.default.post(name: NSNotification.Name("DetailViewNew"), object: nil)
            }
        
        completionHandler()
    }

In SettingsDetailView (where the notification is triggered and setup)

func configureNewAlert() {
    let center = UNUserNotificationCenter.current()
    
    center.removeAllDeliveredNotifications()
    center.removeAllPendingNotificationRequests()

        let content = UNMutableNotificationContent()
        content.title = "Header"
        content.body = "Test"
        content.sound = UNNotificationSound.default
    
    
    if let selectedHour = Calendar.current.dateComponents([.hour], from: userData.wakeUpTime).hour, let selectedMinute = Calendar.current.dateComponents([.minute], from: userData.wakeUpTime).minute{
        
            var dateComponents = DateComponents()
            dateComponents.hour = selectedHour
            dateComponents.minute = selectedMinute
        
        let open = UNNotificationAction(identifier: "open", title: "Open ", options: .foreground)
        let cancel = UNNotificationAction(identifier: "cancel", title: "Close", options: .destructive)
        let categories = UNNotificationCategory(identifier: "action", actions: [open,cancel], intentIdentifiers: [])
        UNUserNotificationCenter.current().setNotificationCategories([categories])
        content.categoryIdentifier = "action"
        

            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
                            
            let randomIdentifier = UUID().uuidString
            let request = UNNotificationRequest(identifier: randomIdentifier, content: content, trigger: trigger)
            
            center.add(request) { error in
                if let error = error {
                    print(error.localizedDescription)
                    
                }
            }
            
        }
}

And in my DetailView (where I want the user to land when tapping the notification)

struct DetailViewNew: View {
    let poemPublisher = NotificationCenter.default.publisher(for: NSNotification.Name("DetailViewNew"))
    @State private var showScreen = false
    
    var body: some View {
        ZStack{
            Text("Text")
        }
        .onReceive(poemPublisher) { notification in
           self.showScreen = true
        }
    }
}

EDIT I removed the categories and action, as I just want to have the user either tap the notification or dismiss it (not custom actions required).

When I do so, the completion handler if response.actionIdentifier == UNNotificationDefaultActionIdentifier does indeed get called. Now the question is how do I route it so it opens the DetailView when tapped?

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

    if response.actionIdentifier == UNNotificationDismissActionIdentifier {
            print ("Message Closed")
        }
        else if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
            print ("App is Open")
            NotificationCenter.default.post(name: NSNotification.Name("DetailViewNew"), object: nil)
            
        }

    
    completionHandler()
}

Any suggestions? Thanks.

0 Answers
Related