2

I've seen a lot a similar questions but I have not found an answer to this specific scenario while running on Mac. If the app is off and a user notification comes in and the user taps on it, then the app is opened. Once the app is opened, how can it capture the notification so that it can handle its contents.

From what I can tell, the notification cannot be retrieved from [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler: or [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:.

When the app is opened from the user tapping on the notification, it also does not seem to open through the UNUserNotificationCenterDelegate functions. I don't see it in either willPresentNotification or didReceiveNotificationResponse and it's not handled by the appDelegate's didReceiveRemoteNotification:fetchCompletionHandler

On iOS in this situation, the notification arrives inside the launchOptions from application:didFinishLaunchingWithOptions. There's key UIApplicationLaunchOptionsRemoteNotificationKey contains the notification data. The same app running on Mac contains a nil launchOptions dictionary.

These are all the places that I've looked but I'm sure I must be missing something.

Lucian Thorr
  • 1,997
  • 1
  • 21
  • 29

1 Answers1

1

While the OS knows it needs to wake up the app because some tapped on a notification, your app is likely setup too late for being the UserNotificationCenterDelegate.

See docs:

You must assign your delegate object to the UNUserNotificationCenter object before your app finishes launching. For example, in an iOS app, you must assign it in the application(_:willFinishLaunchingWithOptions:) or application(_:didFinishLaunchingWithOptions:) method of your app delegate. Assigning a delegate after the system calls these methods might cause you to miss incoming notifications

Like what's happening now for you is:

  • user taps on notification
  • app gets launched
  • in the app's didFinishLaunching the delegate isn't set yet, so didReceiveNotificationResponse isn't called.

tldr for any delegate/callback that can wake up the app (e.g. UserNotification, CoreLocation, etc.), the setup/registration for the callbacks needs to happen before didFinishLaunching

mfaani
  • 33,269
  • 19
  • 164
  • 293
  • That's a great point but that does not seem to be the case in my situation. I am setting the appDelegate as the `UNUserNotificationCenterDelegate` in `didFinishLaunching`. For the sake of experimenting, I've moved it into `willFinishLaunching` but I'm not seeing any difference on Mac. – Lucian Thorr Nov 10 '21 at 16:53
  • I've never done mac-catalyst. I don't know if things are meant to be different. FWIW you can get the notification using `UIApplicationLaunchOptionsRemoteNotificationKey` and then just pass that yourself to you the delegate functions, but that's not a very ideal solution in my mind. – mfaani Nov 10 '21 at 18:04