Swift UNUsernotification applicationIconBadgeNumber始终显示一个

时间:2017-09-19 12:38:34

标签: ios swift unusernotificationcenter

我已设置用户通知。他们交付得很好,但应用程序图标上的徽章始终是一个。 这是我的代码:

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

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

当使用时点击按钮我安排通知:

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

这是scheduleNotif函数

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

任何想法为什么徽章将始终显示一个,并且在递送通知时永不递增?

谢谢

1 个答案:

答案 0 :(得分:1)

我认为你需要增加applicationIconBadgeNumber。所以替换

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

人:

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