【问题标题】:Handle iOS Push Notification when app in backgroud在后台处理应用程序时的 iOS 推送通知
【发布时间】:2019-12-17 12:34:05
【问题描述】:

当应用程序在后台/运行时,我必须处理推送。我正在使用 firebase 和本机推送服务。设置能力 - 后台获取。我收到推送的所有内容,当应用程序在后台运行时,我可以在推送视图上打开应用程序,并在应用程序运行时处理推送。但我必须执行以下操作:

应用运行时。

接收推送、显示警报、注销用户。 有效!

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

didReceiveRemoteNotification 方法中处理此操作。 有效!

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

didReceiveRemoteNotification 方法中处理此操作。 不起作用!

我怎样才能得到推送当应用程序在后台/关闭时。保存数据(例如徽章计数或推送可以在 AppDelegate 变量中)。并在 applicationDidBecomeActive 方法中得到这个?

【问题讨论】:

  • 希望这有帮助.. developer.apple.com/documentation/usernotifications/….当应用程序在后台时,它对我有用。
  • @AnilArigela;这有帮助。请在答案中添加您的评论。
  • 修复了一个问题! 要发送后台通知,请使用仅包含内容可用键的 aps 字典创建远程通知 必须在您的有效负载中。现在,当应用程序关闭/终止时我遇到了另一个问题,这不起作用。

标签: ios swift firebase push-notification appdelegate


【解决方案1】:

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

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 中将您的 AppDelegate 设置为委托:

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

希望这能有所帮助 :-)

【讨论】:

  • 当应用关闭时用户点击推送消息时检测。但是我需要在应用程序关闭时保存推送中的数据,并在应用程序关闭时点击应用程序图标获取数据
  • 推送通知时无法保存数据,因为是由操作系统管理的。唯一的方法是保存数据,然后在用户点击推送通知时获取它。当然,如果用户不点击推送,您可能会丢失数据。尝试实现一种方法,在每次用户启动您的应用程序以向服务器询问数据时启动
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 2017-10-31
  • 2018-07-04
相关资源
最近更新 更多