如何在接收通知时更新tabBar徽章值

时间:2017-02-20 18:51:31

标签: ios swift2 xcode8

如何在接收通知以更新swift 2.3中的标签栏徽章值时进行后台API调用?

我使用以下代码更新远程通知上的徽章价值:

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    pushDictionary = userInfo

    NSNotificationCenter.defaultCenter().postNotificationName("PushNotification", object: self, userInfo: userInfo)

    let pushNotification = PushNotification(dictionary: pushDictionary!)
    notification.subtitleText = pushNotification.message

    if application.applicationState == UIApplicationState.Inactive {

        if pushNotification.type != nil {
            if pushNotification.type == "vc1"{
                self.tabBarViewController.selectedIndex = 0
                self.tabBarViewController.tabBar.items![0].badgeValue = "1"
                self.tabBarViewController.selectedViewController?.viewWillAppear(true)
            }
            if pushNotification.type == "vc2"{
                self.tabBarViewController.selectedIndex = 1
            }
            if pushNotification.type == "vc3"{
                self.tabBarViewController.selectedIndex = 2
            }
        }
    }

如果用户处于前台和后台,我希望接收通知时增加徽章值。提前致谢

我正在更新ViewController中的徽章值:

    let unreadFeeds = feedsDictionary?.objectForKey("UnReadFeeds") as! NSInteger
      if unreadFeeds > 0 {

      self.tabBarController?.tabBar.items?[0].badgeValue = String(unreadFeeds)
                if #available(iOS 10.0, *) {
                    self.tabBarController?.tabBar.items![0].badgeColor = UIColor(red: 219/255.0, green: 90/255.0, blue: 41/255.0, alpha: 1)
                } else {
                    // Fallback on earlier versions
                }

1 个答案:

答案 0 :(得分:3)

每当用户收到通知时,您将获得远程通知委托方法的回调。更新标签栏徽章,如下所示。

self.tabBarController?.tabBar.items![0].badgeValue = "YourBadgeValue"

如果您的视图控制器位于navigation controller内,则必须使用

self.navigationController!.tabBarItem.badgeValue = "YourBadgeValue"
相关问题