I want to store a value in userdefault to show badge value on tab item. Code working fine when app is in foreground and background state. But its not storing value in userdefault in Inactive state. So, when i launch app i am not able to get received notifications counts after the app termination.
Added following code in AppDelegate
class:
public static var badgeValue: String? {
get {
return UserDefaults.standard.string(forKey: "updateBadgeValue")
}
set(newValue) {
UserDefaults.standard.set(newValue, forKey: "updateBadgeValue")
UserDefaults.standard.synchronize()
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if let badgeValue = AppDelegate.badgeValue {
AppDelegate.badgeValue = String(Int(badgeValue)!+1)
} else {
AppDelegate.badgeValue = "1"
}
NotificationCenter.default.post(name: NSNotification.Name("updateBadgeValue"), object: nil)
}
and fetching value by following code in UITabBarController
class:
override func viewDidLoad() {
super.viewDidLoad()
updateBadgeValue()
}
func updateBadgeValue() {
if UIApplication.shared.applicationIconBadgeNumber != 0 {
self.tabBar.items![0].badgeValue = String(UIApplication.shared.applicationIconBadgeNumber)
}
NotificationCenter.default.removeObserver(self, name: NSNotification.Name("updateBadgeValue"), object: nil).
NotificationCenter.default.addObserver(self, selector: #selector(updateBadgeValue), name: NSNotification.Name("updateBadgeValue"), object: nil)
}
//Remove observer is removing previous added observer so that previous added observer will call again and again. If i dont remove observer then when i come on UITabBarController class it will add new observer every time.