将本地通知徽章计数增加到 1

Increase local notification badge count past 1

我目前正在尝试在我的应用程序中实现本地通知,并运行解决由于某种原因无法将徽章计数器增加到 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()
    }

}

出于某种原因,当多个通知被成功安排并确实传递时,无论传递的通知的实际数量如何,徽章计数器最多只会增加 1。

是否有正确的方法来管理徽章数量,这不是吗?

您应该考虑一下您的代码的作用。您没有增加徽章计数,只是每次都将其设置为 1。

这是实现徽章计数的一种方法:

  1. 您需要一种方法来跟踪当前徽章计数。一种简单的解决方案是使用用户默认值。

  2. 当您安排新通知时,您需要增加 徽章计数,而不是将其设置为静态值。

  3. 您应该为您的通知设置增加的徽章计数。

  4. 当应用程序打开时,您应该将徽章计数重置为零。

    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:) 方法中,您在应用程序启动时将徽章计数重置为零:

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


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

}