我目前正尝试在我的应用中实现本地通知,但遇到了由于某种原因无法将角标(Badge)计数器增加到 1 以上的问题。
这是我配置和安排通知的方法。
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()
}
}
出于某种原因,当多个通知被成功安排并确实传递时,无论传递的通知的实际数量如何,角标(Badge)计数器只会增加到 1。
是否有一种正确的方法来管理角标(Badge)数量,这不是吗?
最佳答案
您应该考虑您的代码的作用。您并没有增加角标(Badge)计数,只是每次都将其设置为 1。
这是实现角标(Badge)计数的一种方法:
您需要一种方法来跟踪当前角标(Badge)计数。一种简单的解决方案是使用用户默认值。
当您安排新通知时,您需要增加角标(Badge)计数,而不是将其设置为静态值。
您应该为通知设置增加的角标(Badge)计数。
当应用程序打开时,您应该将角标(Badge)计数重置为零。
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 }
并且在您的 application(_:didFinishLaunchingWithOptions:)
方法中,您在应用启动时将角标(Badge)计数重置为零:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.applicationIconBadgeNumber = 0
userDefaults.set(0, forKey: "NotificationBadgeCount")
}
关于ios - 将本地通知角标(Badge)计数增加到 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60351044/