0

I've a common function in UIViewController extension. I'm calling this function from tab bar controller and view controller. This works when called from view controller but doesn't work when called from tab bar controller. Control goes to else Error: tabItems. I can't figure out what's wrong, any other way of doing it so that it works when called from tab controller?

class MainTabBarController: UITabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.updateBadges()
}

extension UIViewController {

    func updateBadges() {
        DispatchQueue.main.async {
            self.setBadge(tab: 1, count: 3)
        }
    }

    func setBadge(tab: Int, count: Int) {
        if let tabItems = self.tabBarController?.tabBar.items {
            print("Inside tabItems")

            let tabItem = tabItems[tab]

            if count != 0 {
                tabItem.badgeValue = String(count)
            } else {
                tabItem.badgeValue = nil
            }
        } else {
            print("Error: tabItems")
        }
    }
}
Dan
  • 475
  • 9
  • 26
  • the extension need not to be for `UIViewController ` as the code is related to `UITabBarController` and making it ` tabController extension , you can access it like this inside any tab `self.tabBarController?.setBadge` – Shehata Gamal Dec 19 '18 at 23:30

1 Answers1

1

The problem is that self.tabBarController is nil for the UITabBarController itself. One possible solution is something like the following:

func setBadge(tab: Int, count: Int) {
    let tabBarController = self as? UITabBarController ?? self.tabBarController

    if let tabItems = tabBarController?.tabBar.items {
        print("Inside tabItems")

        let tabItem = tabItems[tab]

        if count != 0 {
            tabItem.badgeValue = String(count)
        } else {
            tabItem.badgeValue = nil
        }
    } else {
        print("Error: tabItems")
    }
}
André Slotta
  • 13,774
  • 2
  • 22
  • 34