Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

APNs: Change the app badge while the app is the foreground

I have an app and a server-side push sender. When new notifications arrive, the server sends an empty push message which only contains a badge update.

When the app is in the background, the badge is successfully updated. However, when the app is in the foreground, the badge is not updated at all - the push is delivered to the app, which discards it.

The obvious workaround is to catch the push and update the badge from within the app. For some technical reasons this would take some time to take effect (development time, app store check time, users who don't frequently upgrade etc.)

I wonder if there's a way to circumnavigate this and update the badge using a server side APNs push regardless of the app state, foreground or background.

Is there a way to change an iOS app badge using a push message, when the app is in the foreground, without handling the push notification from within the app?

like image 331
Adam Matan Avatar asked Mar 11 '23 07:03

Adam Matan


1 Answers

This can only be achieved through application delegate methods defined in your AppDelegate

Deprecated in iOS 10

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

or,

- (void)application:(UIApplication *)application 
didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;

The above delegate functions gets called when app is in foreground there you can decode your Push Payload and assign the application badge as follows

[UIApplication sharedApplication].applicationIconBadgeNumber=[[userInfo objectForKey:@"aps"] valueForKey:@"badge"];

Cheers.

like image 55
iphonic Avatar answered Mar 24 '23 17:03

iphonic