How can I tell whether user opened an iOS app using push notification? I want to track using analytics when the user opens the app through push notification. I’m using pusher.com to send the push notification. What app delegate function can I add my amplitude tracking code?
Here’s what I have
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let notification = launchOptions?[.remoteNotification] as? [AnyHashable: Any] {
Amplitude.instance().logEvent("Push Opened", withEventProperties: notification)
}
return true
}
Unfortunately it doesn’t cover when the app is in the background. How can I cover that?
application(_:didFinishLaunchingWithOptions:)
That method is only call on a app launch, so that means you already handled "Cold-Start" cases.
To handle background scenario:
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 1) Set UNUserNotificationCenter delegate
UNUserNotificationCenter.current().delegate = self
/* the rest of the code */
...
return true
}
userNotificationCenter(_:didReceive:withCompletionHandler:)
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
/* Track Events here!!! */
...
completionHandler()
}
}
As the document of the delegation method says:
The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from application:didFinishLaunchingWithOptions:.
In my opinion, I think we can remove the tracking in the application(_:didFinishLaunchingWithOptions:)
, it's not tested, please verify.