我正在从Firebase获得远程推送通知。我正在尝试在应用程序图标中获取徽章计数。在Firebase中,可以选择将徽章记为波纹管
目前,我没有要测试的设备。我的问题是,如果我每次都将1作为徽章计数,它将自动在应用程序图标上增加徽章计数吗?如果没有,那么如何使用firebase增加它。
您想使用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
设置为零
SomeVC:
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
}