ios - 将本地通知角标(Badge)计数增加到 1

标签 ios swift xcode notifications swiftui

我目前正尝试在我的应用中实现本地通知,但遇到了由于某种原因无法将角标(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)计数的一种方法:

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

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

  3. 您应该为通知设置增加的角标(Badge)计数。

  4. 当应用程序打开时,您应该将角标(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/

相关文章:

ios - 我怎样才能让这两个功能很好地协同工作?

ios - SceneKit:Shademodifier 忽略 Xcode 7 中的自定义全局函数

objective-c - 如何从 Tweetbot 制作一个像这样的 NSWindow?

使用 Zip 插件编译 Cordova iOS 应用程序 - 找不到 aes/aes.h

ios - 无法重现 App Store 审核团队遇到的(IPv6?)连接问题

ios - Apple Push Notification Service 和多个服务器的问题

ios - 使用 Swift 在 iOS 应用程序中上传图像作为个人资料照片

ios - 完全禁用 Swift 按下 'backspace'

ios - 如何压缩多个数据而不是多个图像?

ios - 无法使用 Xcode 7.3.1 在我的 Swift 2 项目中使用 "po"检查变量 - 加载辅助函数时出错