2

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

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

2 回答 2

3

推送通知有两种方法被调用

  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
于 2017-10-06T04:56:40.200 回答
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
于 2017-10-06T05:15:10.930 回答