用户关系管理

更新时间:2022-09-07

用户登录后,可进行添加联系人、获取好友列表等操作。

本文介绍如何通过环信即时通讯 IM Flutter SDK 管理好友关系,包括添加、同意、拒绝、删除、查询好友,以及管理黑名单,包括添加、移出、查询黑名单。

环信即时通讯 IM React Native SDK 提供 EMContactManager 类实现好友的添加移除,黑名单的添加移除等功能。主要方法如下:

  • addContact 申请添加好友;
  • deleteContact 删除好友;
  • acceptInvitation 同意好友申请;
  • declineInvitation 拒绝好友申请;
  • getAllContactsFromServer 从服务器获取好友列表;
  • getAllContactsFromDB 从本地数据库中获取好友列表;
  • addUserToBlockList 添加用户到黑名单;
  • removeUserFromBlockList 将用户从黑名单移除;
  • getBlockListFromServer 从服务器获取黑名单列表。

开始前,请确保满足以下条件:

  • 完成 SDK 初始化,并连接到服务器,详见 快速开始
  • 了解环信即时通讯 IM 的使用限制,详见 使用限制

添加好友

  1. 用户添加指定用户为好友
// 用户 ID
String userId = "foo";
// 申请加为好友的理由
String reason = "Request to add a friend.";
try{
  await EMClient.getInstance.contactManager.addContact(userId, reason);
} on EMError catch (e) {
}
  1. 对方收到申请,同意成为好友,或者拒绝成为好友

同意成为好友示例代码如下:

// 用户 ID
String userId = "bar";
try{
  await EMClient.getInstance.contactManager.acceptInvitation(userId);
} on EMError catch (e) {
}

拒绝成为好友示例代码如下:

// 用户 ID
String userId = "bar";
try{
  await EMClient.getInstance.contactManager.declineInvitation(userId);
} on EMError catch (e) {
}
  1. 接收方对于同意,申请方收到监听事件 onContactInvited

// 注册监听
EMClient.getInstance.contactManager.addEventHandler(
  "UNIQUE_HANDLER_ID",
  EMContactEventHandler(
    onFriendRequestAccepted: (userId, reason) {},
  ),
);

// 移除监听
EMClient.getInstance.contactManager.removeEventHandler("UNIQUE_HANDLER_ID");
  1. 对方拒绝,收到监听事件 onFriendRequestDeclined

// 注册监听
EMClient.getInstance.contactManager.addEventHandler(
  "UNIQUE_HANDLER_ID",
  EMContactEventHandler(
    onFriendRequestDeclined: (userId) {},
  ),
);

// 移除监听
EMClient.getInstance.contactManager.removeEventHandler("UNIQUE_HANDLER_ID");
  1. 添加好友流程到此结束。

获取好友列表

  1. 从服务器获取好友列表
List<String> contacts = await EMClient.getInstance.contactManager.getAllContactsFromServer();
  1. 从本地数据库中获取好友列表

List<String> contacts = await EMClient.getInstance.contactManager.getAllContactsFromDB();

删除好友

删除好友建议执行双重确认,以免发生误删操作。删除操作是不需要对方同意或者拒绝操作的。

// 用户 ID
String userId = "tom";
// 是否保留聊天会话
bool keepConversation = true;
try {
  await EMClient.getInstance.contactManager.deleteContact(
    userId,
    keepConversation,
  );
} on EMError catch (e) {
}

将对方加入黑名单,对方将无法发送消息给自己

// 用户 ID
String userId = "tom";
try {
  await EMClient.getInstance.contactManager.addUserToBlockList(userId);
} on EMError catch (e) {
}

查看当前用户黑名单列表

  1. 使用本地缓存获取黑名单列表
try {
  List<String> list =
      await EMClient.getInstance.contactManager.getBlockListFromDB();
} on EMError catch (e) {
}
  1. 通过服务器获取黑名单列表

try {
  List<String> list =
      await EMClient.getInstance.contactManager.getBlockListFromServer();
} on EMError catch (e) {
}

从黑名单中移除用户,用户发送消息等行为将恢复

String userId = "tom";
try {
  await EMClient.getInstance.contactManager.removeUserFromBlockList(userId);
} on EMError catch (e) {
}