2

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)
     }
 }
LC 웃
  • 18,888
  • 9
  • 57
  • 72
Daniel.wu
  • 31
  • 1
  • 5
  • You can follow this tutorial https://eladnava.com/send-push-notifications-to-ios-devices-using-xcode-8-and-swift-3/ and https://stackoverflow.com/questions/44490391/swift-3-turn-off-badge-alert-sound – iPatel Oct 06 '17 at 04:51

2 Answers2

3

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
Bhumesh Purohit
  • 491
  • 1
  • 8
  • 26
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
Prakash Tripathi
  • 137
  • 1
  • 13