当我的应用程序处于后台或关闭时,当远程推送通知到达时从有效负载中获取数据
Posted
技术标签:
【中文标题】当我的应用程序处于后台或关闭时,当远程推送通知到达时从有效负载中获取数据【英文标题】:Get data from payload when remote push notification arrive while my app is in background or closed 【发布时间】:2016-10-06 15:21:25 【问题描述】:接收远程推送通知时,我需要从有效负载中捕获数据,在 ios 9 上,我使用 func 执行此操作: didReceiveRemoteNotification 在使用 swift 3.0 的 IOS 10 上,我实现了这两个功能。
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
print("\(notification.request.content.userInfo)")
completionHandler([.alert, .badge, .sound])
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
print("User Info = ",response.notification.request.content.userInfo)
completionHandler()
第二个函数仅在用户触摸推送时执行
当我的应用处于后台甚至关闭时,当推送通知到达时,我需要捕获数据。
问候。 问候
【问题讨论】:
【参考方案1】:当收到推送通知并且您的应用未运行时,您需要在 didFinishLaunchingWithOptions 中实现通知逻辑:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
// Called when a notification is tapped and the app wasn't running, not in foreground neither in background.
if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: AnyObject]
// your logic here!
【讨论】:
【参考方案2】:func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
// Capture payload here something like:
let appState = userInfo["appState"] as? String
print(appState!)
// Do something for every state
if (application.applicationState == UIApplicationState.active)
print("Active")
else if (application.applicationState == UIApplicationState.background)
print("Background")
else if (application.applicationState == UIApplicationState.inactive)
print("Inactive")
completionHandler(.noData)
【讨论】:
【参考方案3】:试试iOS10的didReceiveRemoteNotification功能:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any])
print(userInfo)
【讨论】:
嗨,我做到了,并且我能够在 aps content-available=1 上的后台 sendind 中从推送通知中捕获数据。但是当应用程序关闭时,它似乎永远不会执行。 嘿@Christian Gonzalez,如果用户自己关闭或终止应用程序,那么我们不能做这样的事情。以上是关于当我的应用程序处于后台或关闭时,当远程推送通知到达时从有效负载中获取数据的主要内容,如果未能解决你的问题,请参考以下文章
如何在应用程序处于后台(ios)时使 FCM 通知正常工作?
当应用程序处于后台时,从推送通知中插入 coredata 记录