如何在 IOS 后台 运行 应用程序被杀死时获取通知负载

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

我有一个问题。从通知中打开应用程序时是否可以获取通知正文,即使该应用程序不在后台 运行。彻底被秒杀了。

您需要根据收到通知时您的应用所处的状态以不同方式处理通知:

如果您的应用不是 运行 并且用户通过点击推送通知启动它,则推送通知会在 application(_:didFinishLaunchingWithOptions:) 的启动选项中传递到您的应用。

如果您的应用 运行 在前台或后台,系统会通过调用 application(_:didReceiveRemoteNotification:fetchCompletionHandler:) 通知您的应用。如果用户通过点击推送通知打开应用程序,iOS可能会再次调用此方法,因此您可以更新UI并显示相关信息。

将以下代码添加到 application(_:didFinishLaunchingWithOptions:) 的末尾,就在 return 语句之前:

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

}

要处理接收推送通知的其他情况,请将以下方法添加到 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)
}

你应该在下面的步骤中休息

1-) 在您的 AppDelegate 中,添加以下代码片段

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

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

3-) "content-avaliable": 1, 添加到你的payload中。

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