0

When notification reach the application, there is no action on badge number. I set background mode on Capabilities.

And there is another problem. This metod does not invoke when app is background mode.

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("Push notification received2: \(userInfo)")
    completionHandler(UIBackgroundFetchResult.noData)
}

PS: UIApplication.shared.applicationIconBadgeNumber is not answer. I know that. The problem is even the push notification received by application, the badge number does not update.

  • 1
    https://stackoverflow.com/questions/14256643/update-badge-with-push-notification-while-app-in-background follow this link please – Mridul Gupta Sep 12 '18 at 07:51
  • Badge number which show on app icon is manage directly by OS, if notification payload send badge number correclty it shows automatically. – Hardik Thakkar Sep 12 '18 at 08:29

1 Answers1

3

APNS doesn't support increment operations for badges. each push notification generated should be setting what the current value should be.

so we need to have a service/server somewhere keeping track of what badges should be for each of your users

for example add the one key of badge in your payload, get the count of your badge and increment the count followed by the example.

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    var currentBadgeNumber: Int = application.applicationIconBadgeNumber
    currentBadgeNumber += Int(userInfo["badge"] as? String ?? "0")!
    application.applicationIconBadgeNumber = currentBadgeNumber
    completionHandler(UIBackgroundFetchResult.noData)
}

for example payload, see the old answer in SO.

Note : didReceiveRemoteNotification is deprecated from iOS10+ onwards, see this for example

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • I use willPresent method now. But It does not invoke when app is on background. – tersintersi Sep 12 '18 at 08:34
  • @tersintersi- sorry for delay reply, if your app is background then this method will be called. `func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {` – Anbu.Karthik Sep 14 '18 at 04:32