Ios – How to clear badge counter on click of app icon in iphone

apple-push-notificationsiosiphoneobjective cswift

We have developed an ios app using phonegap and have implemented push notification functionality in our app.
Push notification works perfectly fine for us. We have configured push notification for both (alerts and badge) and both works fine.
When we click on the alert list it redirects us to the application and clears all the notifications from the alert list and also the badge counter is set to 0.

But when we click on the application icon(badge counter) it brings app to the foreground but the badge counter and alerts are not getting cleared.

We have used following code in didFinishLaunchingWithOptions method (in appdelegate.m file)that clears out the alerts and resets the badge only on-click of alerts

 application.applicationIconBadgeNumber = 0;

can anyone provide us the solution that shows same behaviour when we click on app icon with badge counter.

Best Answer

To clear the badge count whenever the application becomes active use delegate method. You can use UIApplicationDelegate in AppDelegate.

call the [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; in either applicationWillEnterForeground nor applicationDidBecomeActive

- (void)applicationWillEnterForeground:(UIApplication *)application

{
 [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
 }

or

- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

Swift

func applicationWillEnterForeground(application: UIApplication) {
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}

or

func applicationDidBecomeActive(application: UIApplication) {
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}

For Swift 3:

UIApplication.shared.applicationIconBadgeNumber = 0

iOS 13 >

func sceneDidBecomeActive(_ scene: UIScene) {
UIApplication.shared.applicationIconBadgeNumber = 0
}

enter image description here