Reputation:
I am getting remote push-notification from firebase. I am trying to get badge count in app icon. In Firebase there is option to give badge count as bellow
As for now i dont have device to test. My question is if i put 1 as badge count every-time will it increment badge count automatically on app icon? if no then how to increment it using firebase.
Upvotes: 3
Views: 10755
Reputation: 19602
You want to use UserDefaults
to keep track of the amount of notifications that come in
1- first register the badge count to UserDefaults
with a value of 0
. I usually register on Login Screen in viewDidLoad with whatever other values that I need to register
var dict = [String: Any]()
dict.updateValue(0, forKey: "badgeCount")
UserDefaults.standard.register(defaults: dict)
2- when your notification comes in from Firebase to your app, update the "badgeCount"
. Here is an example when the notification comes in to 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- whatever logic in whichever vc that you use to acknowledge when the user has viewed the notification, reset UserDefaults'
badgeCount back to zero. Also set the UIApplication.shared.applicationIconBadgeNumber
to zero
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
}
Information for UIApplication.shared.applicationIconBadgeNumber
Upvotes: 1