Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase local notification badge count past 1

I'm currently trying to implement local notifications into my app and ran into the issue of not being able to increase the badge counter past 1 for some reason.

Here is my method for configuring and scheduling notifications.

func scheduleNotification() {

    let content = UNMutableNotificationContent()
    content.title = "\(self.title == "" ? "Title" : self.title) is done"
    content.subtitle = "Tap to view"
    content.sound = UNNotificationSound.default
    content.badge = 1

    if self.isPaused {
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: self.currentTime, repeats: false)
        let request = UNNotificationRequest(identifier: self.notificationIdentifier.uuidString, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request)
    } else {
        removeNotification()
    }

}

For some reason, when multiple notifications are successfully scheduled and indeed delivered, the badge counter only increases up to 1, regardless of the actual number of delivered notifications.

Is there a proper way to manage the badge count and this just ain't it?

like image 286
Alexey Primechaev Avatar asked Oct 29 '25 22:10

Alexey Primechaev


1 Answers

You should think about what your code does. You are not increasing the badge count, you just set it to 1 each time.

Here is one way to implement badge counting:

  1. You need a way to keep track of the current badge count. One simple solution is to use User Defaults.

  2. When you schedule a new notification you need to increase the badge count and not set it to a static value.

  3. You should set that increased badge count for your notification.

  4. When the app opens you should reset the badge count to zero.

    func scheduleNotifications(notificationBody: String, notificationID: String) {
    
        //Your other notification scheduling code here...
    
        //Retreive the value from User Defaults and increase it by 1
        let badgeCount = userDefaults.value(forKey: "NotificationBadgeCount") as! Int + 1
    
        //Save the new value to User Defaults
        userDefaults.set(badgeCount, forKey: "NotificationBadgeCount")
    
        //Set the value as the current badge count
        content.badge = badgeCount as NSNumber
    
    }
    

And in your application(_:didFinishLaunchingWithOptions:) method you reset the badge count to zero when the app launches:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {


     UIApplication.shared.applicationIconBadgeNumber = 0
     userDefaults.set(0, forKey: "NotificationBadgeCount")

}
like image 69
lajosdeme Avatar answered Oct 31 '25 15:10

lajosdeme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!