tersintersi
tersintersi

Reputation: 43

Show badge number when notification received

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.

Upvotes: 0

Views: 610

Answers (1)

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

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

Upvotes: 3

Related Questions