let content = UNMutableNotificationContent()
content.badge = 0 // your badge count

此代码在applicationWillEnterForeground中,目的是通过将数字设置为0来擦除徽章,以便用户重新输入应用程序,但是事实证明,它完全没有用,因为它不会更新应用程序图标上的徽章...

我现在已恢复为iOS 9代码,它的工作原理很吸引人。此外,看来,使用新框架,您实际上必须发送要更新的徽章编号的通知,这实际上是不切实际的..如果我错了,请有人纠正我

此外:
 let content = UNMutableNotificationContent()
        TableViewController.numberBadges += 1
        content.title = "Title"
        content.body = "this is the body ..."
        content.badge = TableViewController.numberBadges as NSNumber?
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let requestidentifier = "myNotification"
        let request = UNNotificationRequest(identifier: requestidentifier, content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request, withCompletionHandler: {error in
            // handle error if there is one
            if((error) != nil){
                print("Error completing notification scheduling: \(error)")
            }else{
                print("Added Notification request successfully with \(content.badge!) badges")
            }

        })

不更新徽章,怎么办?

最佳答案

在iOS 10和11上,通过安排带有UNNotificationRequest的通知来擦除徽章存在问题。文档说将badge对象的UNMutableNotificationContent属性设置为0会在触发通知时擦除徽章,但这似乎不起作用。通过实验,我在两个iOS版本中都找到了解决此错误的方法。

如您所见,在iOS 10 / Xcode 8上,将该值设置为0无效,此标志将继续显示其当前值。我发现如果将其设置为-1:

let content = UNMutableNotificationContent()
content.badge = -1

那么在触发通知时,它确实会删除徽章。

在iOS 11 / Xcode 9上,将badge属性设置为小于1的任何值都不会执行任何操作-徽章将继续显示其当前值。我发现,如果将标志设置为0并同时设置sound属性,例如:
let content = UNMutableNotificationContent()
content.badge = 0
content.sound = UNNotificationSound.default()

然后徽章将被删除。在我的应用中,我已使用requestAuthorization方法请求显示徽章的权限,但我没有请求播放声音的权限,因此触发通知时实际上没有声音播放。 (如果您的应用确实请求播放声音的权限,并且您不希望在删除徽标时播放声音,则我不知道解决方法是什么。)

更新:我还通过模拟器检查了iOS 11的变通办法也适用于iOS 10。

只要badge属性设置为正数,我还没有其他任何问题(尚未!)来计划用于更新徽章的通知。

10-07 19:20
查看更多