简体   繁体   中英

How to get notification payload when app is killed not running in background in IOS

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)
}

you should fallow below steps

1-) in your AppDelegate, added below code snipped

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
    }

2-)Sign&Capability -> Background Modes, allows 允许背景模式

3-) "content-avaliable": 1, add to your payload.

{"aps":{"alert":"Testing.. (40)","content-available":1,"badge":1,"sound":"default"}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM