Search code examples
iosswiftkey-value-observinguiapplicationdelegateuiapplication

Swift observe UIApplication property


Is it possible to somehow observe property of UIApplication.sharedApplication() in swift?

I need to track UIApplication.sharedApplication().applicationIconBadgeNumber to update my app UI based on that number, but whenever this property is changed UI is not affected.

My code regarding this:

private var badgeCount: String = String(UIApplication.sharedApplication().applicationIconBadgeNumber)

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.notificationsButton.setTitle(self.badgeCount, forState: .Normal)
}

Solution

  • This is solution may work for you add iconBadgeNumber computed variable to UIApplication via extension and it will set the real variable and notify your app of changes

    extension UIApplication
    {
      var iconBadgeNumber:Int { set{self.applicationIconBadgeNumber = iconBadgeNumber
                NSNotificationCenter.defaultCenter().postNotificationName("BageNumberChanged", object: nil)
            } get{return self.applicationIconBadgeNumber}}
    }
    
    //Add this at Observer
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #Selector(Controller.Method), name: "BageNumberChanged", object: nil)