主题
React Native 从零接入晞晗IM
本页演示在 React Native 应用中连接 XHIM,并发送第一条文字消息。
1. 准备信息
开始前请准备:
- Server URL,例如
https://im.example.com; - App ID;
- 当前登录用户的 User ID;
- 由你的业务后台签发 XHIM 短期凭证的接口。
不要把 Business Key、管理员密钥或长期 Token 写进 App。
2. 安装
bash
npm install @xihansoftware/xhim-react-native @react-native-community/netinfo生产应用还需要一个按账号隔离的本地消息存储。未配置持久化存储时,应用仍能在线收发消息,但重启后不会保留离线数据。
3. 创建应用级客户端
客户端应由应用级 Service 或账号 Store 持有,不要在 React 组件每次渲染时重复创建。
ts
import { AppState } from 'react-native'
import NetInfo from '@react-native-community/netinfo'
import { XHIMReactNativeClient } from '@xihansoftware/xhim-react-native'
export const xhim = new XHIMReactNativeClient({
server: 'https://im.example.com',
appId: 'your-app-id',
accountHint: currentUser.id,
credentialProvider: async ({ forceRefresh }) =>
accountApi.fetchXHIMCredential({ forceRefresh }),
environment: {
fetch: globalThis.fetch,
createWebSocket: (url, protocols) => new WebSocket(url, protocols),
currentAppState: () => AppState.currentState,
observeAppState: (listener) => {
const subscription = AppState.addEventListener('change', listener)
return () => subscription.remove()
},
observeNetworkAvailable: (listener) =>
NetInfo.addEventListener((state) => {
if (state.isConnected) listener()
})
}
})credentialProvider 使用 App 已有登录态访问你的业务后台。SDK 需要刷新凭证时会再次调用它。
4. 连接并监听事件
ts
await xhim.connect()
const off = xhim.on('sync', () => {
messageStore.reloadVisibleConversations()
})页面卸载时调用 off() 取消页面监听;账号会话由应用级 Service 继续持有。
5. 发送第一条消息
ts
const conversationId = await xhim.directConversation('bob')
const sent = await xhim.sendText(conversationId, '你好,XHIM')
console.log(sent.serverMessageId)6. 退出账号
ts
off()
xhim.disconnect()换号时先断开旧客户端,再创建新账号对应的客户端和存储。
7. 常用方法
| 任务 | 方法 |
|---|---|
| 创建或获取单聊 | directConversation(peerUserId) |
| 发送文字 | sendText(conversationId, text) |
| 发送自定义消息 | sendMessage(conversationId, message) |
| 查询历史消息 | messages(conversationId, options) |
| 监听 SDK 事件 | on(eventName, listener) |
| 断开账号 | disconnect() |
8. 常见问题
- 重复收到事件:检查是否在组件渲染时重复创建 Client 或重复注册监听;
- 应用重启后没有本地消息:检查是否配置了账号隔离的持久化本地存储;
- 后台恢复后没有重连:确认
observeNetworkAvailable能收到真实网络恢复事件; - 连接返回未授权:让业务后台刷新短期凭证,不要在 App 中保存管理密钥。
需要修改页面、状态管理或消息渲染时,再阅读客户端二次开发指南。