Skip to content

Instantly share code, notes, and snippets.

@chucknado
Last active June 3, 2016 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chucknado/487086d14b3a71575669e12bbbcaad97 to your computer and use it in GitHub Desktop.
Save chucknado/487086d14b3a71575669e12bbbcaad97 to your computer and use it in GitHub Desktop.
Example "unread chats" badge from sample app at https://github.com/zendesk/ios_sdk_demo_apps/tree/master/ChatBadgeCount
// FirstViewController.swift
// ChatBadgeCount
//
// Created by Barry Carroll on 30/05/2016.
// Copyright © 2016 chatbadge. All rights reserved.
// See the tutorial at https://support.zendesk.com/hc/en-us/articles/220080968
import UIKit
import ZDCChat
class FirstViewController: UIViewController, UITabBarControllerDelegate {
var currentMessageCount: NSInteger = 0
var badgeTabBarItem: UITabBarItem!
override func viewDidLoad() {
super.viewDidLoad()
// Grab a reference to the UITabBarItem which shows the badge count.
badgeTabBarItem = tabBarController?.tabBar.items?[1]
tabBarController?.delegate = self
}
/*
This method will calculate the number of unread messages and display them on a badge.
*/
func chatEvent() {
let newMessageCount = ZDCChat.instance().session.dataSource().agentMessageCount()
var unreadCount: NSInteger = 0
if (currentMessageCount != 0 && newMessageCount != 0) {
if (newMessageCount > currentMessageCount) {
unreadCount = newMessageCount - currentMessageCount
badgeTabBarItem.badgeValue = String(unreadCount)
}
}
}
/*
When this appears we assume that the chat has been hidden. We then start to listen
for any incoming messages.
*/
override func viewDidAppear(animated: Bool) {
currentMessageCount = ZDCChat.instance().session.dataSource().agentMessageCount()
ZDCChat.instance().session.dataSource().addObserver(
self,
forChatLogEvents: #selector(chatEvent)
)
}
/*
When this disappears we assume that we're going back to the chat, so we can
assume that we have read all of the unread messages
*/
override func viewWillDisappear(animated: Bool) {
// Reset the unread count and set the badge to nil so it stops showing
currentMessageCount = 0
badgeTabBarItem.badgeValue = nil
// Removes the observer because we don't need it
ZDCChat.instance().session.dataSource().removeObserverForChatLogEvents(self)
}
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
// Don't allow the chat to be 'popped under'
if (tabBarController.selectedIndex == 1 && viewController.isKindOfClass(UINavigationController)) {
return false
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment