Our iOS Chat SDK has a floating widget that shows you how many unread messages have been received. This works well but you can also do the same thing using a badge. This tutorial shows you how using a sample application on GitHub.
Getting started
The tutorial builds on the quick start guide for the iOS Chat SDK. If you followed along with the guide, you’ll be in a good place to follow this tutorial.
The sample app
The sample app in the quick start guide is small and contains FirstViewController.swift , which acts as a main screen, and SecondViewController.swift , which acts as the chat screen.
Here's the completed view controller implementing most of the changes, followed by explanations of how the code works. For the complete sample app, see the ChatBadgeCount project in our samples repo on GitHub.
How it works
When the main screen is displayed, the
viewDidAppear
function runs and prompts the Chat SDK to start listening for incoming chat events using the chat APIs :
currentMessageCount = ZDCChat.instance().session.dataSource().agentMessageCount()
ZDCChat.instance().session.dataSource().addObserver(
self,
forChatLogEvents: #selector(chatEvent)
)
When the main screen is about to disappear, the
viewWillDisappear
function runs and tells the Chat SDK to stop listening:
// 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)
When a chat event is received, the
chatEvent
method is called. This first part of the method gets the number of messages that the agent has sent, if any:
let newMessageCount = ZDCChat.instance().session.dataSource().agentMessageCount()
The app uses the
currentMessageCount
variable to store the number of agent messages when the user navigated away from the screen, so you can use these two values to figure out the number of unread messages whenever you get a chat event, and then display the number in a badge:
var unreadCount: NSInteger = 0
if (currentMessageCount != 0 && newMessageCount != 0) {
if (newMessageCount > currentMessageCount) {
unreadCount = newMessageCount - currentMessageCount
badgeTabBarItem.badgeValue = String(unreadCount)
}
}
Wrapping up
We hope the sample code is useful. The Chat SDK team will be publishing more sample code to the iOS SDK demo apps repo on GitHub so check back often. We’d also love to see if you have some cool samples to share too.
1 Comments
what about in Android?
Please sign in to leave a comment.