How to update badge number when receive push notification

三世轮回 提交于 2019-12-24 08:28:13

问题


I need help finishing this piece of code so the app will show badge number when a push notification is received, I can receive push notification, but just no badge on app, here is the code

 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:


There is the two Methods are Called for Push notification

  1. Foreground Method
  2. Background Method

1.Foreground Method.

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

Get content of Request of Notification

let content = notification.request.content

2.Background Method

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

Get content of Request of Notification

let content = response.notification.request.content

Get Badge Count

let badge = content.badge as! Int



回答2:


Follow these steps to set badge count in iOS :

1.Implement logic to calculate count in backend and send that count through Push notification like :

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

2.Get Badge count from Push notification response :

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

3.set badge count in didReceiveRemoteNotification method :

UIApplication.sharedApplication().applicationIconBadgeNumber = badgeCount


来源:https://stackoverflow.com/questions/46598362/how-to-update-badge-number-when-receive-push-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!