简体   繁体   中英

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?

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")

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM