0

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.

  • 1. What does "its not working on Inactive state"? What's going wrong, and how do you know? 2. Please show enough code that we can understand what you are doing. Your code has some mysterious variables such as `NC_UPDATE_BADGE_VALUE`; we need to know their value. – matt Oct 05 '18 at 16:52
  • Also what on earth is the point of saying `removeObserver(); addObserver()`? If you want to stay on as an observer, just do nothing. – matt Oct 05 '18 at 16:55
  • @matt I updated code. Please check. – Manisha Sharma Oct 06 '18 at 05:10

0 Answers0