直播间场景实践

直播间场景实践:以完整业务场景串起 IMLib 能力:直播间、红包、语音转文字、内容审核与 AI 工具接入。

适用场景​

  • 需要按场景快速搭出可运行 Demo
  • 评估多能力组合(会话/消息/事件/上传)的接入成本

前置条件​

  • 已完成 IMLib 初始化与连接
  • 服务端 appkey 可用并有测试用户
  • 宿主具备基础 UI 容器

直播间场景以「聊天室」承载:进入房间 joinChatroom、离开 leaveChatroom、消息走 sendMessage/sendTextMessage、历史用 getHistoryMessages;直播状态与成员权限由业务服务端维护,IMLib 只负责房间内实时消息与事件。

  • 房间生命周期:创建/加入/退出以聊天室接口为准;游客模式由业务签发只读 Token。
  • 消息与历史:聊天室消息实时投递,历史按聊天室维度查询;离线补发策略以服务端配置为准。
  • 与融云直播间示例的差异:RTC/连麦与礼物面板不在 IMLib 范围内,需业务/RTC SDK 接入。

能力与 API​

以下操作来自冻结的 sdk-imlib.json;签名与参数逐字取自 sdk-bindings.json → bindings.ios.imlib.methodMap。

操作Swift 签名返回参数
joinChatroomfunc joinChatroom(chatroomId: String) async -> RcResult<IMPChatroom>ChatroomchatroomId:string
leaveChatroomfunc leaveChatroom(chatroomId: String) async -> RcResult<Void>nullchatroomId:string
sendMessagefunc sendMessage(conversationType: IMPConversationType, targetId: String, content: IMPMessageContent, options: IMPSendOptions?) async -> RcResult<IMPMessage>MessageconversationType:ConversationType, targetId:string, content:Content, options?:{clientMsgId?:string, channelId?:string}
getHistoryMessagesfunc getHistoryMessages(conversationType: IMPConversationType, targetId: String, options: IMPHistoryOptions?) async -> RcResult<IMPHistoryPage>{messages:Message[], hasMore:bool}conversationType:ConversationType, targetId:string, options?:{limit?:uint32, beforeSeq?:uint64, channelId?:string}

完整字段与错误码见 API 参考;示例可直接复制到 Swift/Objective-C 工程。

Swift / Objective-C 示例​

let res = await client.joinChatroom(chatroomId: "cr_2001")
if res.code != 0 { print("IM 调用失败:\(res.msg ?? "")") }
[client joinChatroomWithChatroomId:@"cr_2001" completion:^(IMPOSResult *result) {
    if (result.code != 0) { NSLog(@"IM 调用失败:%ld %@", (long)result.code, result.msg); }
}];
let res = await client.leaveChatroom(chatroomId: "cr_2001")
if res.code != 0 { print("IM 调用失败:\(res.msg ?? "")") }
[client leaveChatroomWithChatroomId:@"cr_2001" completion:^(IMPOSResult *result) {
    if (result.code != 0) { NSLog(@"IM 调用失败:%ld %@", (long)result.code, result.msg); }
}];
错误处理

IMLib 不 throw:检查 res.code。常见:1002 Token 无效、1001 参数错误、3001 未连接(可重试)、3002 超时。完整码表见 状态码。

与融云对应页 / 差异​

项内容
融云页面ios-imlib/tutorial/liveroom(直播间场景实践)
融云接口状态边界页(非接口页)
我方对应joinChatroom、leaveChatroom、sendMessage、getHistoryMessages(本项目可用 op,非融云同名接口)
差异说明直播间场景实践;引用的聊天室 KV/封禁通知能力已计入 chatroomKV、moderation 页
能力缺口(如实标注)

融云该页描述的能力未完全在 IMLib 102 op / 16 事件中覆盖:直播间场景实践;引用的聊天室 KV/封禁通知能力已计入 chatroomKV、moderation 页。本页上方列出的 op 为本项目可用能力(替代/部分覆盖),不是融云同名接口。

相关错误码​

错误码名称含义处理
1001INVALID_PARAMETER参数错误修正参数/权限后重试
1002INVALID_TOKENToken 无效或已过期修正参数/权限后重试
1007MESSAGE_TOO_LARGE消息体过大(上限 5KB)修正参数/权限后重试
1009GROUP_MUTED你已被禁言修正参数/权限后重试
1010SENSITIVE_WORD内容包含敏感词修正参数/权限后重试
3001SDK_NOT_CONNECTED长连接未就绪可重试(退避)
3002SDK_TIMEOUT请求超时可重试(退避)
3003SDK_NETWORK_ERROR网络错误可重试(退避)

排查建议​

  • 先确认 client.getConnectionStatus() 为 connected,再调用业务 op。
  • 按错误码区分:1001/1007 修正参数;1002/1003 重新登录;3001/3002 退避重试。
  • 本地数据异常时先查看本地库路径与迁移日志,再清缓存复现。

相关页面​