uni-app x
更新时间: 2026/11/19 16:39:54
本文介绍如何初始化 NIM uni-app x V10 系列网易云信即时通讯 SDK(简称 NIM SDK)。
调用时机
对 NIM SDK 进行初始化的时机,是在调用各项即时通讯功能之前。一般情况下,在应用的生命周期内,仅需进行一次初始化。
前提条件
初始化 NIM uni-app x SDK 前,请确保您已经完成了以下操作:
- 集成 SDK。
- 在 网易云信控制台 上 创建应用,并获取 App Key 和 App Secret。
- 注册网易云信 IM 账号,获取 IM 账号和 token。
初始化
调用 initNIMSDKJson 方法创建实例并实现初始化。
TypeScriptinitNIMSDKJson(options: UTSJSONObject): Promise<NIMResult<UTSJSONObject>>
options 的通用配置参数如下
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
appKey |
string |
是 | 云信 SDK AppKey。 |
enableV2CloudConversation |
boolean |
否 | 是否使用云端会话;三端默认都是 false,即使用本地会话。 |
私有配置见 uts 自身定义:
- Android 扩展:
AndroidSDKOptions - iOS 扩展:
IOSSDKOptions - HarmonyOS 扩展:
HarmonySDKOptions
登录
调用 loginWithProviders 登录。
tsloginWithProviders(
accountId: string,
token: string,
option: UTSJSONObject | null,
tokenProvider: ((accountId: string) => string) | null,
loginExtensionProvider: ((accountId: string) => string) | null
): Promise<NIMResult<V2NIMLoginResult>>
示例代码
tsimport {
initNIMSDKJson
} from '@/uni_modules/nim-uts-sdk'
const APP_KEY = 'your_app_key'
const ACCOUNT_ID = `YOUR_ACCOUNT_ID` // 账号
const STATIC_TOKEN = `YOUR_STATIC_TOKEN` // 登录 token
// 初始化
initNIMSDKJson({ appKey: APP_KEY } as UTSJSONObject).then((res) => {
if (res.code == 200) {
console.log('init ok', res)
} else {
console.error('init fail', res)
}
})
const loginService = new V2NIMLoginService()
// 静态登录
loginService!.loginWithProviders(ACCOUNT_ID, STATIC_TOKEN, {
authType: 0,
syncLevel: 0
} as UTSJSONObject, (currentAccountId : string) : string => {
return currentToken
}, null).then((res) => {
if (res.code == 200) {
uni.showToast({ title: '登录成功', icon: 'success' })
} else {
uni.showToast({ title: res.desc.length > 0 ? res.desc : '登录失败', icon: 'none' })
}
printResult('loginWithProviders', JSON.stringify(res))
})
// 如果是动态登录, 可以这么写
loginService!.loginWithProviders(ACCOUNT_ID, STATIC_TOKEN, {
authType: 1,
syncLevel: 0
} as UTSJSONObject, (currentAccountId : string) : string => {
return STATIC_TOKEN
}, null).then((res) => {
if (res.code == 200) {
uni.showToast({ title: '登录成功', icon: 'success' })
} else {
uni.showToast({ title: res.desc.length > 0 ? res.desc : '登录失败', icon: 'none' })
}
printResult('loginWithProviders', JSON.stringify(res))
})
此文档是否对你有帮助?




