![](/img/trans.png)
[英]Firebase Push Notification Increase Badge Count When Receive Notification
[英]Does Firebase push-notification badge count increase automatic in iOS?
您想使用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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.