Search code examples
iosuilocalnotification

How to remove badge but not remove all notifications?


If the user has alert style set to Banners. They can receive more than 1 notification without them being prompted to clear it.

I saw same apps, If the click on the latest one & it opens the App, only clear just this one notification, and remove badge;

If I use

[UIApplication sharedApplication].applicationIconBadgeNumber = 0;

It will clear all notifications that have received.

So how to remove badge but not remove all notifications?


Solution

  • OK, I find the answer in this

    add new notification which badge is -1.

    - (void)applicationDidEnterBackground:(UIApplication *)application {
          if (iOS11) {
                UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
                content.badge = @(-1);
                UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"clearBadge" content:content trigger:nil];
                [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                }];
          } else {
                UILocalNotification *clearEpisodeNotification = [[UILocalNotification alloc] init];
                clearEpisodeNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
                clearEpisodeNotification.timeZone = [NSTimeZone defaultTimeZone];
                clearEpisodeNotification.applicationIconBadgeNumber = -1;
                [[UIApplication sharedApplication] scheduleLocalNotification:clearEpisodeNotification];
          }
    }
    

    Then the badge will be removed,but other notifications not.