2

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)
}
zhuber
  • 5,364
  • 3
  • 30
  • 63

2 Answers2

2

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)
Mohamed DiaaEldin
  • 1,061
  • 1
  • 10
  • 23
0

enter image description here

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.


     UIApplication.sharedApplication().applicationIconBadgeNumber = 5

    return true
}
 override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)

        let badgeCount: String = String(UIApplication.sharedApplication().applicationIconBadgeNumber)

        let notificationsButton: UIButton = UIButton (type: UIButtonType.Custom)

        notificationsButton.addTarget(self, action: "tapBarNotificationsButton", forControlEvents: UIControlEvents.TouchUpInside)

        notificationsButton.frame = CGRectMake(0, 0, 25, 25)

        notificationsButton.backgroundColor = UIColor.blackColor()

        notificationsButton.setTitle(badgeCount, forState: .Normal)

        let barnotificationsButton = UIBarButtonItem(customView: notificationsButton)

        self.navigationItem.setRightBarButtonItem(barnotificationsButton, animated: true)



    }
Hasya
  • 9,792
  • 4
  • 31
  • 46