查看收到的通知后,将徽章值重置为0

时间:2017-04-30 08:22:04

标签: ios swift

我在过去几天因为收到badge时试图增加notification值而被卡住了。我有一个观察者设置为每次收到通知时增加指定的徽章值。它完美无缺:

//adds the observer. if it goes off then add one to the notification badge
    NotificationCenter.default.addObserver(forName: PRIVATE_NOTIFICATION, object: nil, queue: nil) { (notification) in
        //increment a variable
        self.privateBadge += 1

        if let notificationTab = self.tabBar.items?[1]{
            if self.tabBar.selectedItem != notificationTab as UITabBarItem {
        notificationTab.badgeValue = "\(self.privateBadge)"
        if #available(iOS 10.0, *) {
            notificationTab.badgeColor = ChatMessageCell.indexedColor
        } else {
            // Fallback on earlier versions
        }
        }}
    }

我的问题是尝试在删除观察者后重置变量(privateBadge)。 在获取通知徽章的选项卡上的viewDidAppear中,我设置了一个方法,可在用户点按该标签后将徽章值重置为0:

//View Will Appear
override func viewWillAppear(_ animated: Bool) {
    //Removes the badgeValue and resets messageBadge to 0 in an attempt to start the loop over.
    if let thisTab = self.tabBarController?.tabBar.items?[1]{
        NotificationCenter.default.removeObserver(self, name: PRIVATE_NOTIFICATION, object: nil)
        thisTab.badgeValue = nil
        tabBarControllerClass.privateBadge = 0
    }
}

badgeValue应该清除,但我的问题是当我收到另一个通知时会发生什么。它不是从0开始并递增到1,而是从它停止的地方开始。因此,例如,如果我收到2个通知,则badgeValue将等于2.如果我使用badgeValue转到该选项卡,它将清除并重置为0,但它不会。相反,下次我收到通知时,它会说3而不是1.

有没有更好的解决方案?我应该设置一个协议/代理系统吗?

1 个答案:

答案 0 :(得分:1)

这看起来像你的坏孩子,

self.privateBadge += 1

你可能忘了把它重新设置为0,

thisTab.badgeValue = nil
self.privateBadge = 0

不确定您的情况是否可行,因为我不知道它是否属于同一类。