PubSub - iOS
PubSub, a property of the Room Class, is used to send and receive messages in a room. Access it withroom.pubSub.- All
PubSubmethods areasync throws. Call them withtry awaitfrom aTaskor anotherasynccontext.
Methods
publish()
func publish(topic: String, message: String, options: PubSubPublishOptions = PubSubPublishOptions(), payload: [String: Any]? = nil) async throws
publish()is used to publish messages on a specified topic in the room.- If you set
persisttotrue, the message is stored for the rest of the room, and participants who join later receive it.
Parameters
-
topic :
- type :
String - Participants can deliver messages to that particular topic.
- type :
-
message :
- type:
String - Any arbitrary message you want to publish.
- type:
-
options :
- type :
PubSubPublishOptions - specifies the options for the message:
- persist:
Bool- Store the message, so participants who subscribe later receive it. Default value:false. - sendOnly:
[String]?- Deliver the message only to these participant IDs.nil(default) sends it to everyone.
- persist:
- type :
-
payload :
- type :
[String: Any]? - specifies the payload for the message. Subscribers receive it in the message's
payload.
- type :
payload must contain only JSON values (strings, numbers, booleans, arrays and dictionaries). Otherwise it is not sent.
Returns
Void
Throws
ERROR_ACTION_PERFORMED_BEFORE_ROOM_JOINED(3035) before you join the room or after you leave it.ERROR_ROOM_RECONNECTING(3065) while the room is reconnecting.PUBSUB_PUBLISH_FAILED(4087) if the message could not be published, for example after a timeout.
Most failures, except ERROR_ROOM_RECONNECTING, are also sent to onError.
Example
let topic = "CHAT"
let text = "Hello World!"
let participantIds = ["<PARTICIPANT-ID>"]
// call this from your send button's action
Task {
do {
try await room?.pubSub.publish(
topic: topic,
message: text,
options: PubSubPublishOptions(persist: true, sendOnly: participantIds),
payload: ["sender": room?.localParticipant.displayName ?? "", "messageType": "text"]
)
} catch {
print("Error while sending private message: \(error)")
}
}
subscribe()
func subscribe(topic: String, listener: PubSubMessageListener, options: PubSubSubscribeOptions = PubSubSubscribeOptions()) async throws
subscribe()is used to subscribe to a topic and receive all the messages of that topic in the room.- A listener can subscribe to a topic only once. Unsubscribe first to subscribe it again.
- The SDK holds the listener weakly. Pass a class instance that you keep alive, such as your view controller.
Parameters
-
topic :
- type :
String - Participants can listen to messages on that particular topic.
- type :
-
listener :
- type :
PubSubMessageListener - in this listener, you will get callbacks with the Pubsub message data of the topic. See PubSubMessageListener.
- type :
-
options :
- type :
PubSubSubscribeOptions. Build it withPubSubSubscribeOptions(oldMessageLimit:realtimeOverflow:maxQueue:newMessageLimit:), or createPubSubSubscribeOptions()and set its fields. - oldMessageLimit:
Int?- How many stored messages to receive.nil(default) receives all of them,0receives none, and a positive number receives the latest ones. - realtimeOverflow:
RealtimeOverflow- What happens when new messages arrive faster than they are delivered..QUEUE(default) buffers them and delivers them in order..DROPdrops messages under load. - maxQueue:
Int?- The buffer size for.QUEUE.nil(default) lets the server decide. It is not allowed with.DROP. - newMessageLimit:
Int- The most new messages to accept per delivery batch.0(default) means no limit.
- type :
Returns
Void- Stored messages of the topic, published with
persistset totrue, arrive throughonOldMessagesReceived(_:info:)of your listener.
Throws
ERROR_INVALID_PARAMETER(3073) ifoptionshas an invalid value, or this listener is already subscribed to the topic.ERROR_ACTION_PERFORMED_BEFORE_ROOM_JOINED(3035) before you join the room or after you leave it.ERROR_ROOM_RECONNECTING(3065) while the room is reconnecting.PUBSUB_SUBSCRIBE_FAILED(4088) if the subscription fails, for example after a timeout.
ERROR_ACTION_PERFORMED_BEFORE_ROOM_JOINED and PUBSUB_SUBSCRIBE_FAILED are also sent to onError.
Example
Task {
do {
//subscribing messages on topic CHAT
try await room?.pubSub.subscribe(topic: "CHAT", listener: self)
// receive only the latest 50 stored messages of the topic NOTIFICATIONS
let options = PubSubSubscribeOptions(oldMessageLimit: 50)
try await room?.pubSub.subscribe(topic: "NOTIFICATIONS", listener: self, options: options)
} catch {
print("Failed to subscribe: \(error)")
}
}
unsubscribe()
func unsubscribe(topic: String, listener: PubSubMessageListener) async throws
unsubscribe()is used to unsubscribe from a topic that you subscribed to previously.- The listener stops receiving messages right away. Unsubscribing a listener that is not subscribed does nothing.
Parameters
-
topic :
- type :
String
- type :
-
listener :
- type :
PubSubMessageListener - The listener that you passed to
subscribe().
- type :
Returns
Void
Throws
- A
VideoSDKError, such asPUBSUB_UNSUBSCRIBE_FAILED(4089), if the server unsubscribe fails. This can happen only when the last listener of the topic is removed. After you have left the room it throwsERROR_ACTION_PERFORMED_BEFORE_ROOM_JOINED(3035), so unsubscribe before you callleave().
Example
Task {
do {
//unsubscribing messages on topic CHAT
try await room?.pubSub.unsubscribe(topic: "CHAT", listener: self)
} catch {
print("Failed to unsubscribe: \(error)")
}
}
PubSubMessageListener
The listener you pass to subscribe() conforms to PubSubMessageListener. Every method has a default implementation, so implement only the ones you need.
onMessageReceived(_ message: PubSubMessage)- Called for each new message on the topic.onOldMessagesReceived(_ messages: [PubSubMessage], info: PubSubHistoryInfo)- Called with the stored messages of the topic after you subscribe, in one or more batches.info.isLastistruefor the last batch. It is not called when the topic has no stored messages.onBatchReceived(_ messages: [PubSubMessage])- Called with a batch of new messages, just beforeonMessageReceived(_:)is called for each of them. It may not be called at all, so handle new messages inonMessageReceived(_:).onMessageDrop(_ info: PubSubMessageDropInfo)- Called when new messages were dropped because the.QUEUEbuffer overflowed.info.droppedCountis the number of dropped messages.
extension RoomViewController: PubSubMessageListener {
func onMessageReceived(_ message: PubSubMessage) {
print("\(message.senderName): \(message.message)")
}
func onOldMessagesReceived(_ messages: [PubSubMessage], info: PubSubHistoryInfo) {
print("Received \(messages.count) stored messages")
}
}
Pubsub message data
id
-
type :
String -
Unique id of the message.
message
-
type :
String -
Message that has been published on the specific topic.
senderId
-
type :
String -
id of a sender who has published this message.
senderName
-
type :
String -
Name of a sender who has published this message.
timestamp
-
type :
String -
Timestamp of when a message has been published.
topic
-
type :
String -
Name of the topic.
payload
-
type :
[String: Any] -
Payload of the message, with additional information.
sendOnly
-
type :
[String] -
The participant IDs the message was sent to. It is empty when the message was sent to every subscriber of the topic.
Got a Question? Ask us on discord

