How to respond to local notification when app is completly closed (not in background)?
When the app is running in the background or foreground everything works fine. But when the app is closed and I'm trying to answer to a notification, only "application didFinishLaunchingWithOptions"
gets called, "userNotificationCenter didRecive response
" isn't answering.
I found this question (How to handle UNNotificationAction when app is closed?) but in my case it doesn't work neither at a real device nor in a simulator.
I also noticed that the function "UNUserNotificationCenter.current().getDeliveredNotifications()"
returns nil
when I'm responding to a notification while app is closed.
For iOS 9 and lower in application(_:didFinishLaunchingWithOptions:)
you would check if launchOptions
contains localNotification: UIApplicationLaunchOptionsKey
. If so you would know that the app just freshly started because of local notification (i.e. user clicked on notification).
For iOS 10+ you must register your UNUserNotificationCenterDelegate
in application(_:willFinishLaunchingWithOptions:)
or application(_:didFinishLaunchingWithOptions:)
.
Your delegate's function:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void)
will be called if your app freshly started or it was just sitting in the background.
The advantage of this new API is that there is only one place to handle local notification actions.