0

Whenever a message is sent between users (device to device), the receiving user gets a notification if the app is not in focus. Along with the notification, the badge value for that tab should increase by 1. In an attempt to do so, I've created a NotificationCenter action that goes off in OneSignal's handleNotificationReceived block (within initLaunchWithOptions) like so:

handleNotificationReceived: { (notification) in
            //Notification
            NotificationCenter.default.post(name: MESSAGE_NOTIFICATION, object: nil)
            print("Received Notification - \(notification?.payload.notificationID ?? "")")
    }, 

and the observer is located within the Messaging tab with a function that increases the tab bar badge:

NotificationCenter.default.addObserver(self, selector: #selector(addBadge), name: MESSAGE_NOTIFICATION, object: nil)

//Adds a badge to the messages bar
func addBadge(){
    self.navigationController?.tabBarController?.tabBar.items?[3].badgeValue = "1"
    if #available(iOS 10.0, *) {
        self.navigationController?.tabBarController?.tabBar.items?[3].badgeColor = ChatMessageCell.indexedColor
    } else {
        // Fallback on earlier versions
    }
}

However, Im still not able to get the badge value for the user to appear

AL.
  • 36,815
  • 10
  • 142
  • 281
Vandal
  • 708
  • 1
  • 8
  • 21

1 Answers1

1

It depends on how your view controller hierarchy is set up. The way you're trying to access badgeValue, it's likely that it's not being set because one of those optional properties is returning nil. Set a breakpoint on that line and inspect their values to learn which one.

If your view controller is embedded in a navigation controller and that navigation controller is the first child in the tab hierarchy, like

UITabBarController -> UINavigationController -> UIViewController

then from the UIViewController you could get to the badge value like this navigationController?.tabBarItem.badgeValue.

navigationController will return the nearest ancestor that is a UINavigationController. If that is the first child controller in the tab hierarchy then its tabBarItem property will return the UITabBarItem for the tab and you can update the badge value there.

//Adds a badge to the messages bar
func addBadge(){
    if let currentValue = navigationController?.tabBarItem.badgeValue {
        let newValue = Int(currentValue)! + 1
        navigationController?.tabBarItem.badgeValue = "\(newValue)"
    } else {
        navigationController?.tabBarItem.badgeValue = "1"
    }

    if #available(iOS 10.0, *) {
        navigationController?.tabBarItem.badgeColor = ChatMessageCell.indexedColor
    } else {
        // Fallback on earlier versions
    }
}