Application icon badge number not increasing : Xcode

Krishna Raj Salim picture Krishna Raj Salim · Apr 18, 2013 · Viewed 28.9k times · Source

I am facing a problem with push notification application badge number value updation.

I am doing like:

-(void)application:(UIApplication *)application 
       didReceiveRemoteNotification:(NSDictionary *)userInfo {

       UIApplicationState state = [application applicationState];
       if (state == UIApplicationStateActive) {
          // do stuff when app is active

       }else{
          // do stuff when app is in background
          [UIApplication sharedApplication].applicationIconBadgeNumber = 
          [UIApplication sharedApplication].applicationIconBadgeNumber+1;  
               /* to increment icon badge number */
       }
 }

But, the icon is showing the badge number as '1' always, and it is not incrementing when more notifications are there/ one notification came after another.

Any advice is appreciable...

Answer

Daniel Martín picture Daniel Martín · Apr 18, 2013

The badge number is set by the operating system when you receive a JSON notification payload that resembles the following:

{
    "aps" : {
        "alert" : "New notification!",
        "badge" : 2
    }
}

As you see, it's the server who is responsible for setting the correct number in the badge key. Your server needs to track or compute the number of pending notifications for each user and generate the badge number before sending the notification to Apple.

The client responsibility is to clear the notification badge, or decrement it, when the user sees a notification. The code to do so is

application.applicationIconBadgeNumber = application.applicationIconBadgeNumber - 1; // Decrement counter

or

application.applicationIconBadgeNumber = 0; // Reset counter assuming the user is able to see all notifications at once.