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()
}
2
Answers
In app’s active and running state, press on Notification in handled by willPresent and didReceive function.
But in app’s closed state if we press on notification, app will launch and we can identify the same using
launchOptions
Hope this info will work for you. Happy Coding 🙂
App Terminated: The app relaunches, and
userNotificationCenter(_:didReceive:withCompletionHandler:)
is invoked directly.https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/usernotificationcenter(_:didreceive:withcompletionhandler🙂
// Handle notification responses when app is running or just launched