How to update badge number when receive push notification

8.7k Views Asked by At

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

There are 2 best solutions below

0
Bhumesh Purohit On

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
0
Prakash Tripathi On

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