Technology Sharing

How to quickly integrate chat session capabilities using uni-app?

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In the era of mobile Internet, instant messaging (IM) functions are an indispensable part of many apps. However, when developing instant messaging apps, developers often face a difficult choice: should they develop applications for each platform separately, or should they develop applications for a certain platform only? The emergence of uni-app provides an efficient answer to this problem. With its concept of "write once, run on multiple platforms", uni-app brings unprecedented convenience to developers.

uni-app is a framework for developing all front-end applications based on Vue.js. It supports compiling to iOS, Android, Web and various mini-program platforms through a set of codes. This "write once, run on multiple terminals" development model not only greatly improves development efficiency, but also reduces maintenance costs. The rapid iteration and hot update functions enable the application to quickly respond to market and user needs and maintain competitiveness.

This article willNetEase Cloud IM uni-app SDKBased on this, we will teach you how to integrate chat session capabilities into the uni-app project.

1. Project Preparation

  1. Register a NetEase Cloud developer account: First, you need toNetEase Cloud Music official websiteRegister a developer account on , create an application, and obtain the App Key and Secret Key.
  1. Install the uni-app development environment: Download and install HBuilderX, which is the official development tool of uni-app.
  1. Integrate NetEase Cloud IM SDK: Integrate the NetEase Cloud IM SDK in the uni-app project. Usually, this can be done by importing the SDK's JavaScript file into the project.

2. Initialize SDK and login authentication

After completing the preparations, we need to perform initialization to ensure that the SDK can correctly and stably interact with NetEase Cloud's backend services.

During this process, the SDK will perform a series of preparations, such as loading necessary resources, establishing a connection with the server, and verifying the identity of the application. Only after the SDK is initialized successfully can your application use the various functions provided by the SDK, such as sending and receiving messages, managing user sessions, etc.

Initialization steps:

  1. Introduce NetEase Cloud IM SDK into the uni-app project.
  2. Initialize the SDK and pass in the App Key.
  3. Implement user login logic and obtain accessToken.

Code example:

import Nim from '@path/to/nim-sdk.js';
// 初始化SDK
Nim.init({
  appKey: 'YOUR_APP_KEY' // 替换为你的App Key
});
// 用户登录函数
async function login(accid, password) {
  try {
    // 调用SDK登录接口获取accessToken
    let loginResult = await Nim.login({
      accid: accid,
      password: password,
      rememberMe: true
    });
    
    // 存储accessToken到本地(这里使用uni-app的API)
    uni.setStorageSync('accessToken', loginResult.accessToken);
    
    console.log('登录成功', loginResult);
    // 成果:用户登录成功,accessToken已被存储,可以进行后续的IM操作
  } catch (error) {
    console.error('登录失败', error);
    // 处理登录失败的情况,例如提示用户重新输入账号密码或检查网络状态
  }
}
// 调用登录函数(这里只是示例,实际开发中你需要从用户输入或其他地方获取accid和password)
login('testUser', 'password123');
// 调用login函数后,将尝试使用提供的accid和password登录,并处理登录结果

3. Friend Management

After initialization, we need to complete the basic actions to implement the instant messaging function, which involves the establishment, management and query of friendships between users. Through these operations, users can easily invite other users to join their social circles and manage their friendships:

(1) Adding friends: This is done by calling the SDK's add friend interface.

let accessToken = uni.getStorageSync('accessToken');
// 添加好友函数
async function addFriend(userId, friendId) {
  try {
    // 检查accessToken是否有效
    if (!accessToken) {
      console.error('accessToken无效或不存在');
      return;
    }
    // 调用SDK添加好友接口
    let result = await Nim.friend.add({
      fromAccid: userId, // 当前用户ID
      toAccid: friendId, // 目标用户ID
      msg: '添加你为好友', // 邀请消息
    }, accessToken);
    
    console.log('添加好友结果', result);
    // 成果:如果成功,result将包含添加好友操作的响应信息
  } catch (error) {
    console.error('添加好友失败', error);
    // 处理添加好友失败的情况,例如提示用户检查网络或重新尝试
  }
}
// 调用添加好友函数(这里只是示例,实际开发中你需要从用户输入或其他地方获取userId和friendId)
addFriend('currentUser', 'targetUser');
// 调用addFriend函数后,将尝试添加指定的friendId为好友,并处理结果

(2) Delete friends: This is done by calling the SDK's delete friend interface.

let accessToken = uni.getStorageSync('accessToken');
// 删除好友函数
async function deleteFriend(userId, friendId) {
  try {
    // 检查accessToken是否有效
    if (!accessToken) {
      console.error('accessToken无效或不存在');
      return;
    }
    // 调用SDK删除好友接口
    let result = await Nim.friend.delete({
      fromAccid: userId, // 当前用户ID
      toAccid: friendId, // 目标用户ID
    }, accessToken);
    
    console.log('删除好友结果', result);
    // 成果:如果成功,result将包含删除好友操作的响应信息
    // 根据返回结果更新本地好友列表(如果需要)
  } catch (error) {
    console.error('删除好友失败', error);
    // 处理删除好友失败的情况,例如提示用户检查网络或重新尝试
  }
}
// 调用删除好友函数(这里只是示例,实际开发中你需要从用户列表或其他地方获取userId和friendId)
deleteFriend('currentUser', 'targetUser');
// 调用deleteFriend函数后,将尝试删除指定的friendId为好友,并处理结果

(3) Get the friend list: This is achieved by calling the SDK's Get Friend List API.

let accessToken = uni.getStorageSync('accessToken');
// 获取好友列表函数
async function getFriendList(userId) {
  try {
    // 检查accessToken是否有效
    if (!accessToken) {
      console.error('accessToken无效或不存在');
      return;
    }
    // 调用SDK获取好友列表接口
    let result = await Nim.friend.getFriendList({
      accid: userId, // 当前用户ID
    }, accessToken);
    
    console.log('好友列表', result);
    // 成果:成功获取好友列表,result将包含好友信息
    // 根据返回结果更新本地好友列表(如果需要)
  } catch (error) {
    console.error('获取好友列表失败', error);
    // 处理获取好友列表失败的情况,例如提示用户检查网络或重新尝试
  }
}
// 调用获取好友列表函数(这里只需要当前用户ID)
getFriendList('currentUser');
// 调用getFriendList函数后,将尝试获取当前用户的好友列表,并处理结果

4. Chat Function

Next, we will implement the core chat capabilities, which involve sending messages, receiving messages, displaying messages, and other steps.

1. Send a text message:

// 发送文本消息函数
async function sendTextMessage(toAccid, content) {
  try {
    // 从本地存储中获取accessToken
    let accessToken = uni.getStorageSync('accessToken');
    
    // 检查accessToken是否有效
    if (!accessToken) {
      console.error('accessToken无效或不存在');
      return;
    }
    // 调用SDK发送文本消息接口
    let result = await Nim.message.sendText({
      toSessionType: Nim.SESSION_TYPE_SINGLE, // 会话类型:单人会话
      toAccid: toAccid, // 目标用户ID
      msgBody: {
        text: content // 消息内容
      }
    }, accessToken);
    
    console.log('发送文本消息结果', result);
    // 成果:如果成功,result将包含发送消息操作的响应信息
  } catch (error) {
    console.error('发送文本消息失败', error);
    // 处理发送文本消息失败的情况,例如提示用户检查网络或重新发送消息
  }
}
// 调用发送文本消息函数(这里只是示例,实际开发中你需要从用户输入或其他界面元素获取toAccid和content)
sendTextMessage('receiverAccid', 'Hello, this is a test message.');
// 调用sendTextMessage函数后,将尝试向指定用户发送文本消息,并处理结果

2. Receive Messages

Receiving messages is usually achieved by listening to events provided by the SDK. Here is an example of listening to text message events:

// 监听文本消息事件
Nim.message.on(Nim.EVENT.NEW_MSG, function(msg) { 
 if (msg.sessionType === Nim.SESSION_TYPE_SINGLE