4

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.

Community
  • 1
  • 1
Szymon W
  • 489
  • 8
  • 15
  • what code do you have now and how are you setting up your notifications? – Scriptable Nov 17 '16 at 10:34
  • Are you setting the `UNNotificationCenter` delegate in `didFinishLaunchingWithOptions` or `willFinishLaunchingWithOptions`? – Paulw11 Nov 17 '16 at 10:40
  • if I understand right u must check launchOptions dictionary in "applicationdidFinishLaunchingWithOptions" method for key @"UIApplicationLaunchOptionsLocalNotificationKey" and if success handle u notification – user3820674 Nov 17 '16 at 11:23
  • I noticed right now that I moved delegate from `didFinishLaunchingWithOptions` to separate function which is called in `didReceive response` function. Thank you guys! – Szymon W Nov 17 '16 at 11:34

1 Answers1

7

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.

stevo.mit
  • 4,681
  • 4
  • 37
  • 47