接收推送通知时如何更新徽章号



我需要帮助完成此代码的帮助,因此当收到推送通知时,该应用程序将显示徽章号,我可以收到推送通知,但是仅在应用程序上没有徽章,这是代码

 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)
     }
 }

有两种方法用于推送通知

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

1.前景方法。

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

获取通知请求的内容

let content = notification.request.content

2.background方法

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

获取通知请求的内容

let content = response.notification.request.content

获取徽章计数

let badge = content.badge as! Int

按照以下步骤在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

最新更新