0
votes

I'd like to update a Badge on a Custom Tab Bar Item when I receive some data. I am able to update the badge on the initial viewDidLoad() but then when I try to call viewDidLoad again later with the data, my tab items are nil. Here is how I have set it up...

class CustomTabBar: UITabBarController {

var count = 0

override func viewDidLoad() {
    super.viewDidLoad()


   print("this prints correctly every time I call reload with the updated count: " + count)


    if let tabItems = self.tabBar.items {

        let tabItem = tabItems[0]
        tabItem.badgeValue = String(count)

    }else{
        print("tab items nil")
    }

}

func  reload(count: Int){
    self.count = count
    viewDidLoad()

}

}

I'm calling reload() from another view controller after I get the data I need.

   func updateBadge(){

    let tabBar = CustomTabBar()

        let username = UserUtil.username
        let db = Firestore.firestore()


        let upcomingContestsRef = db
            .collection("NBAContests")
            .whereField("EnteredUsers", arrayContains: username)
            .whereField("Stage", isEqualTo: 2)

        upcomingContestsRef.getDocuments()
            {
                (querySnapshot, err) in

                if let err = err
                {
                    print("Error getting documents: \(err)");
                }
                else
                {
                    print("count is " + String(querySnapshot!.count))

                    tabBar.reload(count: querySnapshot!.count)

                }

        }

}

I've check that viewDidLoad is getting called each time in custom tab bar controller, but after the initial load I don't have access to change the tab items anymore.

Does anyone know whats going on?

I've check out these similar questions

Reload / Refresh tab bar items in a ViewController ?

Setting badge value in UITabBarItem in UIViewController

1

1 Answers

0
votes

This creates

let tabBar = CustomTabBar()

a new instance instead you need

guard let tabBar = self.tabBarController as? CustomTabBar else { print("returned") ; return }