Skip to main content
Version: 4.x.x

Notify Attendees in Realtime - iOS

During a livestream, you may want to broadcast a message to all the viewers at once.

Let us see how we can use PubSub to implement this functionality. If you are not familiar with the PubSub mechanism, you can follow this guide.

Notifying Attendees​

  1. We will publish the message that the sender typed in the text field to the topic NOTIFY_ATTENDEES.
extension RoomViewController {
// Button that sends the typed message to all the viewers when tapped
@IBAction func notifyAttendeesTapped(_ sender: Any) {
let message = messageTextField.text ?? ""
Task {
do {
try await room?.pubSub.publish(topic: "NOTIFY_ATTENDEES", message: message)
} catch {
print("publish error: \(error)")
}
}
}
}
  1. Now let us subscribe to the NOTIFY_ATTENDEES topic after joining, and show an alert to all the viewers displaying the message posted by the speaker.
extension RoomViewController: RoomEventListener {
/// Room joined
func onRoomJoined() {
//...
Task {
do {
try await room?.pubSub.subscribe(topic: "NOTIFY_ATTENDEES", listener: self)
} catch {
print("subscribe error: \(error)")
}
}
}
}

extension RoomViewController: PubSubMessageListener {
func onMessageReceived(_ message: PubSubMessage) {
if(message.topic == "NOTIFY_ATTENDEES"){
self.showToast(message: "Message: \(message.message)", font: .systemFont(ofSize: 18))
}
}
}

extension UIViewController {
func showToast(message: String, font: UIFont) {
let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 125, y: self.view.frame.size.height - 100, width: 250, height: 50))
toastLabel.font = font
toastLabel.textAlignment = .center;
toastLabel.text = message
self.view.addSubview(toastLabel)
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
toastLabel.removeFromSuperview()
}
}
}

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