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