nathanwhy
nathanwhy

Reputation: 6144

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?

Upvotes: 0

Views: 1300

Answers (2)

nathanwhy
nathanwhy

Reputation: 6144

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.

Upvotes: 0

Raymond Liao
Raymond Liao

Reputation: 1795

Here is another sample should working for iOS 11(code in Swift 4.1):

if #available(iOS 11.0, *) {
   let content = UNMutableNotificationContent()
   content.badge = -1
   let request = UNNotificationRequest(identifier: "clearBadge", content: content, trigger: nil)
   UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
} else {
   UIApplication.shared.applicationIconBadgeNumber = -1
}

Upvotes: 1

Related Questions