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

Ahm*_*med 2 ios uilocalnotification swift

我有个问题。即使应用程序没有在后台运行,当您从通知打开应用程序时是否可以获取通知正文。它被彻底杀死了。

小智 5

您\xe2\x80\x99将需要以不同的方式处理通知,具体取决于您的应用程序收到时所处的状态\xe2\x80\x99:

\n\n

如果您的应用程序未运行\xe2\x80\x99t,并且用户通过点击推送通知来启动它,则推送通知将传递到您的应用程序的 launchOptions 中application(_:didFinishLaunchingWithOptions:)

\n\n

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

\n\n

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

\n\n
// Check if launched from notification\nlet notificationOption = launchOptions?[.remoteNotification]\n\n// 1\nif let notification = notificationOption as? [String: AnyObject],\n  let aps = notification["aps"] as? [String: AnyObject] {\n\n  // 2\n  print(aps)\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

要处理接收推送通知的其他情况,请将以下方法添加到 AppDelegate:

\n\n
func application(\n  _ application: UIApplication,\n  didReceiveRemoteNotification userInfo: [AnyHashable: Any],\n  fetchCompletionHandler completionHandler:\n  @escaping (UIBackgroundFetchResult) -> Void\n) {\n  guard let aps = userInfo["aps"] as? [String: AnyObject] else {\n    completionHandler(.failed)\n    return\n  }\n  print(aps)\n}\n
Run Code Online (Sandbox Code Playgroud)\n