Skip to main content
Version: 2.0.x

Chat using PubSub - iOS

For the communication or any kind of messaging in between the participants, VideoSDK provides pubSub class which use Publish-Subscribe mechanism and can be used to develope wide varitey of functionalities. For example, participants could use it to send chat messages to each other, share files or other media, or even trigger actions like muting or unmuting audio or video.

Now we will see, how we can use PubSub to implement Chat functionality. If you are not familiar with the PubSub mechanism and pubSub class, you can follow this guide.

Implementing Chat

Group Chat

  1. First step in creating a group chat is choosing the topic which all the participants will publish and subscribe to send and receive the messages. We will be using CHAT as the topic for this one.
  2. On the send button, publish the message that the sender typed in the TextField field.
import InputBarAccessoryView
import MessageKit
import UIKit
import VideoSDKRTC

class ChatViewController: MessagesViewController {
// MARK: - Properties
private let currentUser = Sender(senderId: "self", displayName: "Me")
/// Meeting Reference
public var meeting: Meeting
public var topic: String
/// Message List
private var messages: [Message] = []
private var metaData: [String: Any]?

// MARK: - Init
init(meeting: Meeting, topic: String, metaData: [String: Any]? = nil) {
self.meeting = meeting
self.topic = topic
self.metaData = metaData
let pubsubMessages = meeting.pubsub.getMessagesForTopic(topic)
messages = pubsubMessages.map({ Message(pubsubMessage: $0) })
super.init(nibName: nil, bundle: nil)
}
}

extension ChatViewController: InputBarAccessoryViewDelegate {
func inputBar(
_ inputBar: InputBarAccessoryView,
didPressSendButtonWith text: String
) {
//...
Task {
do {
try await meeting.pubsub.publish(
topic: "CHAT",
message: text,
options: ["persist": true]
)
} catch {
print("Error while sending message: \(error)")
}
}
// Clear the input bar and reload the collection view
inputBar.inputTextView.text = ""
//...
}
}

// Helper class to get updated messages
class onPubsubMessagGetPrint {
static let shared = onPubsubMessagGetPrint()
@Published var pubsubMessage: PubSubMessage? {
didSet {
messageUpdated?(pubsubMessage)
}
}
var messageUpdated: ((PubSubMessage?) -> Void)?
private init() {}
}
  1. Next step would be to display the messages others send. For this we have to subscribe to that topic i.e CHAT and display all the messages.
class ChatViewController: MessagesViewController {
override func viewDidLoad() {
super.viewDidLoad()
//..
onPubSubMessageReceived()
}
}

extension ChatViewController: InputBarAccessoryViewDelegate {
func onPubSubMessageReceived() {
onPubsubMessagGetPrint.shared.messageUpdated = {
[weak self] pubsubMessage in
guard let self = self, let pubsubMessage = pubsubMessage else { return }
let message = Message(pubsubMessage: pubsubMessage)
if message.sender.senderId != self.currentUser.senderId {
self.messages.append(message)
}
if messages.isEmpty != false {
self.messages.removeLast()
}
}
}
}

extension LiveStreamViewController: MeetingEventListener {
func onMeetingJoined() {
Task {
await meeting?.pubsub.subscribe(topic: "CHAT", forListener: self)
}
}
}

extension LiveStreamViewController: PubSubMessageListener {
func onMessageReceived(_ message: VideoSDKRTC.PubSubMessage) {
switch message.topic {
case "CHAT":
onPubsubMessagGetPrint.shared.pubsubMessage = message
}
}
}
  1. Final step in the group chat would be unsubscribe to that topic, which you had previously subscribed but no longer needed. Here we are unsubscribe to CHAT topic on activity destroy.
extension LiveStreamViewController: MeetingEventListener {
func onMeetingLeft() {
//...
Task {
await meeting?.pubsub.unsubscribe(topic: "CHAT", forListener: self)
}
//...
}
}

Private Chat

In the above example, if you want to convert into the private chat between two participants, then all you have to do is pass sendOnly parameter in options.

class ChatViewController: MessagesViewController {
private func sendMessageTo(participant: Participant) {
//...
let options: [String: Any] = ["persist" : false, "sendOnly" : [participant.id]]
Task {
try await self.meeting?.pubsub.publish(topic: "CHAT", message: "Hello!", options: options)
}
}
}

Downloading Chat Messages

All the messages from the PubSub which where published with persist : true and can be downloaded as an .csv file. This file will be available in the VideoSDK dashboard as well as throught the Sessions API.

API Reference

The API references for all the methods and events utilised in this guide are provided below.

Got a Question? Ask us on discord