Swift UNUsernotification applicationIconBadgeNumber displays always one

2k Views Asked by At

I've set the user notification. They got deliver well but the badge on the app icon is always one. Here's my code:

let center = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .badge, .sound];

center.requestAuthorization(options: options) {
        (granted, error) in
        if !granted {
            // ask for permission
  }
}

When the use click the button i schedule the notif:

 @IBAction func saveBtnPressed(sender: UIButton) {
    scheduleNotif()
}

Here's the scheduleNotif function

 func scheduleNotif() {
    let dateformatter = DateFormatter()
    dateformatter.dateStyle = DateFormatter.Style.medium
    dateformatter.timeStyle = DateFormatter.Style.short
    let dateFromString = dateformatter.date(from: selectDateTextField.text!)
    let fireDateOfNotification: Date = dateFromString!

    //Notif are enabled
    let content = UNMutableNotificationContent()
    content.title = notifTitleTextField.text!
    content.body = notifNoteTextView.text
    content.sound = UNNotificationSound.default()
    content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber

    var trigger: UNCalendarNotificationTrigger
    var triggerDate = DateComponents()
    trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
    let titleNospace = notifTitleTextField.text?.replacingOccurrences(of: " ", with: "")
    var identifier = titleNospace
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    self.center.add(request, withCompletionHandler: { (error) in
        if let error = error {
            print(error.localizedDescription)
        }
    })
}

Any idea why the badge will always display one and never increment as the notifications are delivered?

Thank you

1

There are 1 best solutions below

1
On

I think you need to increment applicationIconBadgeNumber. So replace

content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber

By:

UIApplication.shared.applicationIconBadgeNumber += 1
content.badge = UIApplication.shared.applicationIconBadgeNumber as NSNumber