我搜索过,但找不到例子。我也尝试过改编此代码(在其他地方推荐(CloudKit 不会将我的徽章计数重置为 0 https://stackoverflow.com/questions/25120070/cloudkit-wont-reset-my-badge-count-to-0):
func resetBadgeCounter() {
let badgeResetOperation = CKModifyBadgeOperation(badgeValue: 0)
badgeResetOperation.modifyBadgeCompletionBlock = { (error) -> Void in
if error != nil {
print("Error resetting badge: \(String(describing: error))")
}
else {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
CKContainer.default().add(badgeResetOperation)
}
这目前有效,但不再受支持,并且可能很快就会消失。
我想也许我应该使用 CKModfyRecordsOperation 或其他一些 CKDatabaseOperation,但我什至不知道如何使用。
我希望这对某人有帮助,因为似乎没有其他解决方案/解决方法。
-
创建一个通知服务扩展 (UNNotificationServiceExtension
)为您的应用程序。它相当简单,并且在中进行了详细描述修改新下发的通知内容 https://developer.apple.com/documentation/usernotifications/modifying_content_in_newly_delivered_notifications。如果您对传入通知进行任何类型的处理,您可能已经有了一个。
-
在扩展中,您通常会在以下位置执行所有通知处理:override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)
. The request
附带content
通知的内容,其中包括徽章号码。然后您可以修改它并传递给contentHandler
要显示。 (如果您不确定如何执行此操作,请检查link https://developer.apple.com/documentation/usernotifications/modifying_content_in_newly_delivered_notifications多于;它有详细的说明和代码。)
-
要在需要时跟踪并重置徽章编号,您需要利用应用程序组(例如group.com.tzatziki
)。这样您就可以在应用程序和扩展程序之间共享数据。在 Xcode 中创建应用程序组可以通过添加相关的能力并在中进行了解释应用扩展编程指南:处理常见场景 https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW1.
-
使用存储机制(在应用程序组内)来跟踪徽章计数,例如UserDefaults
,并在扩展中使用它来更新徽章计数。在前述的override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)
,你可以这样写:
let badgeNumber = UserDefaults(suiteName: "group.com.tzatziki")?.value(forKey: "badgeNumber") as? NSNumber ?? NSNumber(integerLiteral: 0)
let badgeNumberInt = badgeNumber.intValue + 1
notificationContent.badge = NSNumber(value: badgeNumberInt)
UserDefaults(suiteName: "group.io.prata")?.setValue(notificationContent.badge, forKey: "badgeNumber")
where notificationContent
是一个实例UNMutableNotificationContent
,源自request.content.mutableCopy() as? UNMutableNotificationContent
- 现在,剩下要做的唯一一件事就是重置应用程序中共享的徽章计数
UserDefaults
and in UIApplication.shared.applicationIconBadgeNumber
.
Cheers!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)