您想使用UserDefaults 来跟踪收到的通知数量
1- 首先将徽章计数注册到UserDefaults,值为0。我通常在 viewDidLoad 的登录屏幕上注册我需要注册的任何其他值
var dict = [String: Any]()
dict.updateValue(0, forKey: "badgeCount")
UserDefaults.standard.register(defaults: dict)
2- 当您的通知从 Firebase 发送到您的应用时,请更新 "badgeCount"。以下是通知进入AppDelegate 时的示例:
// this is inside AppDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// A. get the dict info from the notification
let userInfo = notification.request.content.userInfo
// B. safely unwrap it
guard let userInfoDict = userInfo as? [String: Any] else { return }
// C. in this example a message notification came through. At this point I'm not doing anything with the message, I just want to make sure that it exists
guard let _ = userInfoDict["message"] as? String else { return }
// D. access the "badgeCount" from UserDefaults that you registered in step 1 above
if var badgeCount = UserDefaults.standard.value(forKey: "badgeCount") as? Int {
// E. increase the badgeCount by 1 since one notification came through
badgeCount += 1
// F. update UserDefaults with the updated badgeCount
UserDefaults.standard.setValue(badgeCount, forKey: "badgeCount")
// G. update the application with the current badgeCount so that it will appear on the app icon
UIApplication.shared.applicationIconBadgeNumber = badgeCount
}
}
3- 无论您使用哪个 vc 中的任何逻辑来确认用户查看了通知,都将 UserDefaults'badgeCount 重置为零。还将UIApplication.shared.applicationIconBadgeNumber 设置为零
一些VC:
func resetBadgeCount() {
// A. reset userDefaults badge counter to 0
UserDefaults.standard.setValue(0, forKey: "badgeCount")
// B. reset this back to 0 too
UIApplication.shared.applicationIconBadgeNumber = 0
}
UIApplication.shared.applicationIconBadgeNumber的信息