ios - Firebase 推送通知徽章计数是否会在 iOS 中自动增加?
问题描述
我收到来自 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
为零
一些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
}
推荐阅读
- elasticsearch - 弹性搜索。获取特定索引字段中的值计数
- node.js - Node.js MySQL 模块,在连接关闭时自动重新连接数据库
- airflow - 气流回填 DAG
- python-3.x - 目标 WSGI 脚本无法使用 Python3 作为 Python 模块 (Flask) (Apache) 加载,找不到修复
- javascript - 如何使用 Axios 从 JSON 中获取数据
- macros - 使用 Macro.var 创建的变量
- ios - 我想在 twitter 之类的顶部添加新项目
- brightway - 删除一个brightway方法,而不仅仅是注销
- powershell - 试图从网页中提取信息
- hibernate - 由于“无法创建与数据库服务器的连接”而导致无法构建 Hibernate SessionFactory。