Skip to main content
Create room posts that enable co-streaming and interactive live room experiences. Room posts support multiple hosts broadcasting together with interactive features like live chat, reactions, and real-time viewer engagement.

Co-Streaming Support

Multiple hosts can broadcast together in a single room

Interactive Collaboration

Enable real-time collaboration between hosts and viewers

Overview

Room posts enable interactive live room experiences with co-hosting capabilities. Create rooms that support multiple broadcasters, live chat, and viewer participation features.

Room Types

TypeDescription
coHostsMultiple hosts can broadcast together simultaneously

Room Statuses

StatusDescription
idleRoom created but not yet live
liveRoom is currently broadcasting
waitingReconnectTemporarily disconnected, awaiting reconnection
endedBroadcast has ended
recordedRecording is available for playback

Parameters

ParameterTypeRequiredDescription
textStringPost content (max 20,000 characters)
roomIdStringID of the created room
targetTypeEnumTarget destination (community or user feed)
targetIdStringTarget ID (null for own feed)
titleStringTitle for the room post
metadataObjectCustom fields for extended functionality
mentionUserIdsSet<String>User IDs to mention in the post
hashtagsArray<String>Hashtags for categorization and discovery
func createRoomPost(room: AmityRoom) async {
    // Build your post structure
    let builder = AmityRoomPostBuilder(
        roomId: room.roomId,
        text: "Join our interactive live room!"
    )
    // Create a room post on the current user feed.
    do {
        let post = try await postRepository.createRoomPost(
            builder,
            targetId: nil,
            targetType: .user,
            title: "Live Discussion Session",
            metadata: nil,
            mentionees: nil
        )
    } catch {
        // Handle error here
    }
}

Creating a Room

Before creating a room post, you need to create a room first using the Room Repository.
func createRoom() async {
    do {
        let room = try await roomRepository.createRoom(
            title: "Interactive Q&A Session",
            description: "Join us for a live discussion",
            thumbnailFileId: nil,
            metadata: nil,
            channelEnabled: true,
            parentRoomId: nil,
            participants: ["userId1", "userId2"]
        )
        // Use room.roomId to create the post
    } catch {
        // Handle error here
    }
}

Co-Host Management

Room posts support co-hosting, allowing multiple broadcasters to stream together. The co-host invitation system uses the same invitation repository as communities, enabling hosts to invite users to broadcast together.

Managing Co-Host Invitations

For Hosts

Send Co-Host Invitation
Hosts can invite a user to join as a co-host during a live session. Co-hosts appear with a special badge in the chat and have broadcasting capabilities.
Co-host invitations are sent one user at a time. To invite multiple co-hosts, call the invitation function for each user.
Parameters
ParameterTypeRequiredDescription
userIdstringYesUser ID to invite as co-host
roomIdstringYesID of the room
do {
    try await room.createInvitation("<user_id>")
    print("Co-host invitation sent successfully.")
} catch {
    print("Failed to send co-host invitation: \(error.localizedDescription)")
}
Get Sent Co-Host Invitations
Hosts can view all co-host invitations they’ve sent to track invitation status.
var token: AmityNotificationToken?
let repository = AmityInvitationRepository(client: client)
token = repository.getInvitations(
    targetId: room.roomId,
    targetType: .room
).observe({ collection, change, error in
    // Observe changes in the invitation collection
})

For Invited Users

Get My Room Invitations
Users can retrieve all their pending room co-host invitations.
var token: AmityNotificationToken?
let repository = AmityInvitationRepository(client: client)
token = repository.getMyRoomInvitations().observe({ collection, change, error in
    // Observe changes in the collection
})
Check Co-Host Invitation Status
Check the status of a room co-host invitation. Status Values
StatusDescriptionUser Action
pendingInvitation awaiting responseCan accept or decline
acceptedUser has acceptedCo-host in room
rejectedUser has declinedNo further action
cancelledHost cancelled invitationNo longer valid
if let invitation = await room.getInvitation() {
    switch invitation.status {
    case .pending:
        print("Co-host invitation is pending.")
    case .approved:
        print("Co-host invitation is approved.")
    case .rejected:
        print("Co-host invitation is rejected.")
    case .canceled:
        print("Co-host invitation is canceled.")
    @unknown default:
        print("Unknown invitation status.")
    }
}
Accept Co-Host Invitation
Accept a pending co-host invitation to join the broadcast.
if let invitation = await room.getInvitation() {
    do {
        try await invitation.accept()
        print("Co-host invitation accepted successfully.")
    } catch {
        print("Failed to accept invitation: \(error.localizedDescription)")
    }
}
Decline Co-Host Invitation
Decline a co-host invitation if unable to join the broadcast.
if let invitation = await room.getInvitation() {
    do {
        try await invitation.reject()
        print("Co-host invitation declined successfully.")
    } catch {
        print("Failed to decline invitation: \(error.localizedDescription)")
    }
}

Getting Broadcaster Data

To start broadcasting in a room, retrieve the broadcaster data which contains the necessary connection information. The response type depends on your room configuration. Broadcast Data Types
TypeDescriptionProperties
CoHostsMulti-host co-streaming sessioncoHostToken, coHostUrl
func getBroadcasterData(roomId: String) async {
    do {
        let broadcastData = try await roomRepository.getBroadcastData(roomId: roomId)
        
        switch broadcastData {
        case .coHosts(let data):
            // Use coHostToken and coHostUrl for multi-host streaming
            let token = data.coHostToken
            let url = data.coHostUrl
            // Connect to LiveKit with these credentials
        }
    } catch {
        // Handle error here
    }
}

Connecting to LiveKit

After retrieving the co-host broadcast data, use the LiveKit client library to connect to the streaming server. The coHostUrl and coHostToken are used to establish the real-time connection.

Install the LiveKit SDK

Before connecting, ensure you have the LiveKit SDK installed in your project.
// Add via Swift Package Manager:
// https://github.com/livekit/client-sdk-swift

// Also add camera and microphone permissions to Info.plist:
// NSCameraUsageDescription
// NSMicrophoneUsageDescription

Connect to the Room

Use the coHostUrl as the WebSocket URL and the coHostToken as the access token to connect.
import LiveKit

func connectToLiveKit(coHostUrl: String, coHostToken: String) async {
    // Create LiveKit Room instance (not to be confused with AmityRoom)
    let liveKitRoom = Room()
    
    do {
        try await liveKitRoom.connect(url: coHostUrl, token: coHostToken)
        print("Connected to LiveKit room successfully")
        
        // Access local participant after connection
        let localParticipant = liveKitRoom.localParticipant
        
        // Start publishing audio/video tracks
        try await localParticipant.setCamera(enabled: true)
        try await localParticipant.setMicrophone(enabled: true)
    } catch {
        print("Failed to connect: \(error.localizedDescription)")
    }
}

Disconnect from the Room

Call disconnect() to leave the LiveKit room when the broadcast ends.
await liveKitRoom.disconnect()
For detailed setup instructions, event handling, and advanced features, refer to the official LiveKit documentation.

Best Practices

  • Plan your room configuration before creating
  • Set appropriate title and description for discoverability
  • Enable chat channel for viewer interaction
  • Prepare participant list for co-hosting sessions
  • Coordinate with co-hosts before going live
  • Establish clear roles and speaking order
  • Test audio and video connections with all hosts
  • Have a backup plan if a co-host disconnects
  • Interact with viewers through live chat
  • Acknowledge questions and comments in real-time
  • Use host and co-host badges for clear identification
  • Encourage participation with calls-to-action
  • Ensure stable internet for all hosts
  • Use good lighting and clear audio
  • Test streaming setup before going live
  • Monitor room status for connection issues

Troubleshooting

Problem: Room creation fails before post creationSolutions:
  • Verify Room SDK is properly initialized
  • Check user permissions for room creation
  • Ensure all required parameters are provided
  • Validate participant user IDs exist
Problem: Post creation fails with invalid room IDSolutions:
  • Verify room was created successfully
  • Check room ID is correctly passed to post creation
  • Ensure room hasn’t been deleted
  • Confirm user has permission to create room posts
Problem: Co-hosts unable to join the roomSolutions:
  • Verify co-host invitation was sent successfully
  • Check co-host has accepted the invitation
  • Ensure broadcaster data is retrieved correctly
  • Validate network connectivity for all hosts
// Check room participants before broadcasting
const unsubscribe = RoomRepository.getRoom(roomId, ({data, loading, error}) => {
  // data is room object
  const participants = data.participants;
    participants.forEach((participant) => {
    console.log(`Participant: ${participant.userId}, Status: ${participant.status}`);
  });
});
Problem: Room stuck in unexpected statusSolutions:
  • Check room status using getRoom API
  • Verify streaming connection is active
  • Use stop API to properly end the room
  • Handle waitingReconnect status appropriately
// Monitor room status
const unsubscribe = RoomRepository.getRoom(roomId, ({data: room, error, loading}) => {
   switch (room.status) {
    case 'idle':
      console.log('Room ready to start');
      break;
    case 'live':
      console.log('Room is broadcasting');
      break;
    case 'waitingReconnect':
      console.log('Connection interrupted, attempting to reconnect');
      break;
    case 'ended':
      console.log('Room has ended');
      break;
    case 'recorded':
      console.log('Recording available');
      break;
  }
});
Problem: Live chat not functioning in roomSolutions:
  • Verify channelEnabled is set to true when creating room
  • Check channel ID is available in room object
  • Ensure users have chat permissions
  • Validate real-time connection is established
// Ensure chat is enabled when creating room
const room = await RoomRepository.createRoom({
  title: 'Live Session',
  liveChatEnabled: true, // Required for chat functionality
  type: 'coHosts'
});

// Access chat channel
if (room.liveChatEnabled && room.channelId) {
  const channel = await ChannelRepository.getChannel(room.channelId);
}

Common Use Cases

Panel Discussions

Host multi-speaker panels with co-streaming support

Interactive Workshops

Collaborative teaching sessions with multiple instructors

Live Interviews

Conduct interviews with remote guests as co-hosts

Community Events

Host community gatherings with featured speakers