从带有Onesignal的接收通知中设置徽章值



每当用户之间发送消息(设备到设备(时,如果应用程序不在焦点中,则接收用户会收到通知。除通知外,该选项卡的徽章值应增加1。在尝试这样做的尝试中,我创建了一个通知中心操作,该操作在Onemignal的 handlenotificationReceivedReceivedReceived block中(在 initlaunchwithoptions中((喜欢:

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

,观察者位于"消息"选项卡中,其功能增加了标签栏:

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
    }
}

但是,我仍然无法获得用户出现的徽章值

这取决于如何设置视图控制器层次结构。您试图访问badgeValue的方式,可能没有设置它,因为这些可选属性之一是返回零。在该行上设置一个断点并检查其值以了解哪个。

如果您的视图控制器嵌入到导航控制器中,并且该导航控制器是标签层次结构中的第一个孩子,例如

uitabbarcontroller-> uinavigationController-> uiviewController

然后,从UiviewController中,您可以像以下navigationController?.tabBarItem.badgeValue一样到达徽章值。

navigationController将返回最近的祖先,该祖先是UinavigationController。如果这是标签层次结构中的第一个子控制器,则其tabBarItem属性将返回TAB的UITABBARITEM,您可以在此处更新徽章值。

//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
    }
}

最新更新