iosswiftfirebase-cloud-messagingapple-push-notifications

How save data in UserDefaults when the user press UNNotificationAction and the app is closed?


If the app is opened or in the background, userNotificationCenter get triggered and the data get saved just fine, but if the app is closed, when the notification comes, and I press one of the action buttons, nothing happens, the data doesn't get saved.

This is the code:

UNUserNotificationCenter.current().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound, .criticalAlert]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (granted, error) in
                if granted {
                    
                }
            })
        
        let PKW = UNNotificationAction(identifier: "PKW", title: "Komme per PKW", options: .foreground)
        let Fuß = UNNotificationAction(identifier: "Fuß", title: "Komme per Fuß", options: .foreground)
        let Rad = UNNotificationAction(identifier: "Rad", title: "Komme per Rad", options: .foreground)
        let nicht = UNNotificationAction(identifier: "Nicht", title: "Komme per Komme nicht", options: .foreground)
        let category = UNNotificationCategory(identifier: "ComeBy", actions: [PKW, Fuß, Rad, nicht], intentIdentifiers: [], options: [])
        UNUserNotificationCenter.current().setNotificationCategories([category])

        application.registerForRemoteNotifications()
func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent: UNNotification,
                                withCompletionHandler: @escaping (UNNotificationPresentationOptions)->()) {
        withCompletionHandler([.alert, .sound, .badge])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler: @escaping ()->()) {
        let eventData = response.actionIdentifier
        switch eventData {
        case "PKW", "Fuß", "Rad", "Nicht":
            UserDefaults.standard.set(eventData, forKey: prefixedKey(UserDefaultsKeys.comeBy.key))
        default:
            break
        }

        
        withCompletionHandler()
    }

enter image description here


Solution

  • The issue was related to @capacitor/ios at the end of the day, since I was trying to implement a custom notifications inside AppDelegate, and to make it work, I had to patch the package, and get ride of any use of UNUserNotificationCenterDelegate