How to increase notification badge number dynamically when local notification is delivered?

Viewed 166

My App sets up multiple notifications via a loop based on a calendar date and time. While everything else is working correctly with this, I cannot seem to get the badge number to increment properly. I have tried using a counter and setting

content.badge = self.counter as NSNumber
... or using ...
content.badge = NSNumber(value: UIApplication.shared.applicationIconBadgeNumber + 1)

but what happens is something like the following:

  1. User gets notification 1,2,3,4,5 and badge number gets set to 5 content.badge = self.counter
  2. User then "clears" notifications 2 and 3 -> and badge number is now 3 via my code (UIApplication.shared.applicationIconBadgeNumber - 1)
  3. When the next notification (number 6) pops up, the badge number SHOULD show 4. It doesn't. It shows 6 because that's what was set via content.badge

What is the proper way to increment the badge number? I've looked at various posts here but they're for push notifications. Mine is for a local notifications. Can I set/update badge number WHEN a notification is actually delivered? I thought about trying this in...

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .badge, .sound])
    
}

...but that seems to only be for in-app notifications. Is there another function that I can do this in?

0 Answers
Related