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

Ale*_*aev 4 xcode notifications ios swift swiftui

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

}
Run Code Online (Sandbox Code Playgroud)

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

有没有适当的方法来管理徽章计数,而这不是吗?

laj*_*eme 7

您应该考虑一下您的代码的作用。您并没有增加徽章数量,只是每次将其设置为 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
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

在您的application(_:didFinishLaunchingWithOptions:)方法中,您可以在应用程序启动时将徽章计数重置为零:

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


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

}
Run Code Online (Sandbox Code Playgroud)

  • 但这仅在通知发送时应用程序正在运行时才有效。当应用程序关闭时传递本地通知时,有没有办法做到这一点? (2认同)