2017-04-17 46 views
0

每當用戶(設備到設備)之間發送郵件時,如果應用程序未處於焦點狀態,接收用戶將收到通知。隨着通知,該標籤的徽章值應增加1在試圖這樣做,我創建了一個通知中心作用,在OneSignal的handleNotificationReceived塊熄滅(內initLaunchWithOptions)像這樣:使用OneSignal從收到的通知中設置徽章值

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

但是,我仍然無法獲得用戶出現的徽章值

回答

1

這取決於您的視圖控制器層次結構如何設置。你試圖訪問badgeValue的方式,很可能它沒有被設置,因爲其中一個可選屬性返回nil。在該行上設置一個斷點並檢查它們的值以瞭解哪一個斷點。

如果您的視圖控制器嵌入導航控制器和導航控制器在標籤層次結構中的第一個孩子,像

的UITabBarController - >的UINavigationController - >的UIViewController

然後從UIViewController中你可以得到到像這樣的徽章值navigationController?.tabBarItem.badgeValue

navigationController將返回最接近UINavigationController的祖先。如果這是選項卡層次結構中的第一個子控制器,那麼它的tabBarItem屬性將返回該選項卡的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 
    } 
}