当应用程序处于后台时处理iOS推送通知



当应用程序在后台/运行时,我必须处理推送。我正在使用 firebase 和本机推送服务。设置功能-后台提取。我正在接收推送的全部内容,当应用程序在后台运行时,我可以在推送视图上打开应用程序录制,并在应用程序运行时处理推送。但我必须实现以下:

应用运行时。

接收推送、显示警报、注销用户。工程!

当应用程序在后台/关闭时。从推送中打开应用。

didReceiveRemoteNotification方法中处理此操作。工程!

当应用程序在后台/关闭时。从应用程序图标打开应用程序时。

didReceiveRemoteNotification方法中处理此操作。不行!.

当应用程序在后台/关闭时,我如何获得推送。保存数据(例如,在 AppDelegate 变量中标记计数或推送罐(。并在应用程序中得到这个成为活动方法?

要处理推送通知,您需要实现两个方法,一个在应用程序关闭时调用,另一个在应用程序处于前台时调用。

extension AppDelegate: UNUserNotificationCenterDelegate {
/// Called when the app receive the notification in foreground
/// - Parameter center: <#center description#>
/// - Parameter notification: <#notification description#>
/// - Parameter completionHandler: <#completionHandler description#>
func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Get aps object
let aps = userInfo["aps"] as! [String : Any]
// Do your stuff here
// This line is NEEDED, otherwise push will not be fired
completionHandler([.alert, .badge, .sound]) // Display notification depending on your needed
}

/// Detect when user tap on a push message when app is closed
/// - Parameter center: <#center description#>
/// - Parameter response: <#response description#>
/// - Parameter completionHandler: <#completionHandler description#>
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Get aps object
let aps = userInfo["aps"] as! [String : Any]
// Do your stuff here
// This line is NEEDED, otherwise push will not be fired
completionHandler()
}
}

在您的didFinishLaunchingWithOptions中,将您的应用程序委托设置为委托:

// Set AppDelegate as UNUserNotificationCenterDelegate
UNUserNotificationCenter.current().delegate = self

希望这能有所帮助 :-)

最新更新