Since iOS 10 and with the UserNotifications framework, detecting wether the user launched the app organically or from a local/remote notification is a bit different than before.
Let’s say I’ve to send an event to my analytics service when user launches the app, I do this using one of these three calls:
- Analytics.trackAppLaunched(source: .organic)
- Analytics.trackAppLaunched(source: .localNotification)
- Analytics.trackAppLaunched(source: .remoteNotification)
I have a NotificationController class that will be the UNUserNotificationCenter delegate. After experimenting a bit with it, I noticed that userNotificationCenter(:didReceive:withCompletionHandler:) is called after application(:didLaunchWithOptions:) but before applicationDidBecomeActive(_:).
In order to not send the event multiple times, we simply need to set a flag when we handle a notification during launch, I called it handledLaunchAnalytics.
https://gist.github.com/cyrilchandelier/ba2c3e61dd26e9864eec2f96818de84e
Let’s just not forget to reset handledLaunchAnalytics when the app is going back to background.
If you know of a better way for doing this, I would be happy to hear about you!