I have added user ID in room metadata from my IOS ...
# ask-ai
m
I have added user ID in room metadata from my IOS app. How do I access that user ID in my backend python?
t
Thanks for reaching out, Rishabh. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey! Could you share a bit more about how you added the user ID to the room metadata in your iOS app? Like, did you use a particular API or method to update the room metadata? Knowing this will really help me guide you on how to access it from your backend Python code. Sources: Job lifecycle | LiveKit Docs | livekit-api/livekit/api/room_service.py
m
Actually you know what just give me code on how to add user ID to metadata on iOS client and then access it in the python backend server
t
Here’s a friendly guide on how you can add a user ID to room metadata in your iOS client and then access it in your Python backend: iOS Client (Swift):
Copy code
import LiveKit

func setUserIdInMetadata(userId: String, forRoom roomId: String) async {
    // Let's create the metadata JSON
    let metadata = ["user_id": userId]
    guard let metadataJson = try? JSONSerialization.data(withJSONObject: metadata, options: []) else {
        print("Oops! Failed to serialize metadata")
        return
    }
    guard let metadataString = String(data: metadataJson, encoding: .utf8) else {
        print("Oops! Failed to convert data to string")
        return
    }

    // Now, create the request
    let request = UpdateRoomMetadataRequest(
        room: roomId,
        metadata: metadataString
    )

    // Use RoomService to send the request
    do {
        let roomService = try await LiveKitAPI().room
        let response = try await roomService.updateRoomMetadata(request)
        print("Great! Successfully updated metadata: \(response)")
    } catch {
        print("Whoops! Error updating metadata: \(error.localizedDescription)")
    }
}
Python Backend:
Copy code
import json
import asyncio
from livekit.api import LiveKitAPI
from livekit.protocol.room import ListRoomsRequest

lkapi = LiveKitAPI()
room_service = lkapi.room

async def get_user_id(room_name: str) -> str | None:
    try:
        rooms = await room_service.list_rooms(ListRoomsRequest(names=[room_name]))
        if not rooms.rooms:
            raise ValueError(f"Room {room_name} not found")
        room = rooms.rooms[0]
        metadata = json.loads(room.metadata)
        return metadata.get("user_id")
    except Exception as e:
        print(f"Sorry, ran into an error retrieving user ID: {e}")
        return None

# Example usage
async def main():
    room_name = "my_room"
    user_id = await get_user_id(room_name)
    print(f"User ID in {room_name}: {user_id}")

asyncio.run(main())
Key Notes: • Make sure the metadata is structured as a JSON object so it’s easy to parse. • On the iOS side, use
UpdateRoomMetadataRequest
to update the room metadata. • On the Python backend, use
RoomService
to get the room metadata and parse it to find the user ID. • Don’t forget to check that you have the right permissions set up for updating and accessing room metadata.
t
How can I set the metadata right when we create the room in iOS Swift code.
t
Hey there! Just a quick heads-up: you can’t set room metadata directly from the iOS Swift client SDK when creating a room. Instead, you’ll want to handle this on the server side. Don’t worry, I’ll walk you through how to do it: Server-Side Room Creation with Metadata:
Copy code
// Example using server-side logic (Node.js SDK)
await livekitService.createRoom({
  name: "my-room",
  metadata: JSON.stringify({
    enable_chat: true,
    creator_identity: "user123",
    allow_participant: false
  })
});
Here’s what you’d do in your iOS app: 1. Make a call to your server endpoint to create the room with the metadata you want. 2. Get the room details and token back from your server. 3. Use the LiveKit iOS SDK to connect to the room. After the room’s all set up, you can grab the metadata in your iOS app like this:
Copy code
let roomMetadata = room.metadata // This is a String? value
If you’d like a hand setting up that server-side endpoint or have any questions, just give me a shout—I’m here to help! Sources: src/test/kotlin/io/livekit/server/RoomServiceClientTest.kt | Room metadata | LiveKit Docs | Room metadata | LiveKit Docs | Room metadata | LiveKit Docs | Sources/LiveKit/Protos/livekit_models.pb.swift