【问题标题】:How to update badge number when receive push notification收到推送通知时如何更新徽章编号
【发布时间】:2017-10-06 04:36:19
【问题描述】:

我需要帮助完成这段代码,以便应用程序在收到推送通知时显示徽章编号,我可以收到推送通知,但应用程序上没有徽章,这是代码

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

if let aps = userInfo["aps"] as? NSDictionary, let _ = aps["alert"] as?   String, let sound = aps["sound"] as? String
         {

             if let systemSound = SystemSoundID(sound) {
             AudioServicesPlayAlertSound(systemSound)
         }

         NotificationCenter.default.post(name: Notification.Name(rawValue: SystemSetting.refreshCouponListNotification), object: nil)

         completionHandler(UIBackgroundFetchResult.newData)
     }
 }

【问题讨论】:

标签: ios badge nsusernotification


【解决方案1】:

推送通知有两种方法调用

  1. 前台方法
  2. 背景方法

1.前景方法。

    func userNotificationCenter(_ center: UNUserNotificationCenter, 
               willPresent notification: UNNotification,withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

获取通知请求的内容

let content = notification.request.content

2.背景方法

func userNotificationCenter(_ center: UNUserNotificationCenter, 
                    didReceive response: UNNotificationResponse, 
withCompletionHandler completionHandler: @escaping () -> Void)

获取通知请求的内容

let content = response.notification.request.content

获取徽章计数

let badge = content.badge as! Int

【讨论】:

    【解决方案2】:

    按照以下步骤在 iOS 中设置徽章计数:

    1.实现逻辑来计算后端计数并通过推送通知发送该计数,例如:

    { "aps" : { "alert" : "You got your Push Message.", "badge" : 9 } }

    2.从推送通知响应中获取徽章计数:

    let pushContent = response.notification.request.content
    let badgeCount = content.badge as! Int
    

    3.在 didReceiveRemoteNotification 方法中设置徽章计数:

    UIApplication.sharedApplication().applicationIconBadgeNumber = badgeCount
    

    【讨论】:

      猜你喜欢
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多