I have a question. Is it possible to get the notification body when you open the app from the notification even if is the app is not running in the background. It is completely killed.
You’ll need to handle a notification differently depending on what state your app is in when it’s received:
If your app wasn’t running and the user launches it by tapping the push notification, the push notification is passed to your app in the launchOptions of application(_:didFinishLaunchingWithOptions:)
.
If your app was running either in the foreground or the background, the system notifies your app by calling application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
. If the user opens the app by tapping the push notification, iOS may call this method again, so you can update the UI and display relevant information.
Add the following code to the end of application(_:didFinishLaunchingWithOptions:)
, just before the return statement:
// Check if launched from notification
let notificationOption = launchOptions?[.remoteNotification]
// 1
if let notification = notificationOption as? [String: AnyObject],
let aps = notification["aps"] as? [String: AnyObject] {
// 2
print(aps)
}
To handle the other case for receiving push notifications, add the following method to AppDelegate:
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler:
@escaping (UIBackgroundFetchResult) -> Void
) {
guard let aps = userInfo["aps"] as? [String: AnyObject] else {
completionHandler(.failed)
return
}
print(aps)
}