Set UITabBarItem Badge

647 views Asked by At

I am using Swift and Parse.com to develop an app for iOS 8.

I have an app with 2 tabs. The second tab queries a table in my Parse database and I want to update the badge value of the second tab based on the number of objects in that Parse Query.

I understand how PFQueries work and how to retrieve the number of objects and such, but I am unsure WHERE (i.e. in what method/function) to place this query and update for the tab item's badge?

Was going to use this code or similar to update the badge value:

var tabArray = self.tabBarController?.tabBar.items as NSArray!
var tabItem = tabArray.objectAtIndex(1) as UITabBarItem
tabItem.badgeValue = "34" // will use the value of my countObjects Parse query

So where about would I insert this code to update the badge? It needs to update the value when the app first loads and then when going to/leaving the 2nd tab's view.

Maybe, is there a function for the tab view that runs when the app first launches before the view is even accessed via the tabBar?

1

There are 1 answers

0
Bannings On

You should be concerned about the life cycle of a view and these three methods:viewDidLoadviewWillAppearviewWillDisappear:

func updateBadgeValue() {
    var tabArray = self.tabBarController?.tabBar.items as NSArray!
    var tabItem = tabArray.objectAtIndex(1) as UITabBarItem
    tabItem.badgeValue = "34" // will use the value of my countObjects Parse query
}

// first loads
override func viewDidLoad() {
    super.viewDidLoad()

    updateBadgeValue()
}

//  the view is about to made visible
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    updateBadgeValue()
}

// the view is about to be removed 
override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    updateBadgeValue()
}