首页 > 解决方案 > Firebase 推送通知徽章计数是否会在 iOS 中自动增加?

问题描述

我收到来自 firebase 的远程推送通知。我正在尝试在应用程序图标中获取徽章计数。在 Firebase 中,可以选择将徽章计数如下所示

在此处输入图像描述

至于现在我没有要测试的设备。我的问题是,如果我每次都将 1 作为徽章计数,它会在应用程序图标上自动增加徽章计数吗?如果没有,那么如何使用firebase来增加它。

标签: iosswiftfirebasefirebase-cloud-messaging

解决方案


您想用来UserDefaults跟踪收到的通知数量

1-首先将徽章计数注册UserDefaults0. 我通常在 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的信息


推荐阅读