6

四、Uniapp+vue+腾讯IM+腾讯音视频开发聊天APP,支持消息收发,音视频通话(附开源源...

 2 years ago
source link: https://segmentfault.com/a/1190000041224925
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

这已经是第四篇了,昨天我们代码总算开了个头,今天我们来开始慢慢实现IM中需要的各个模块,今天我们来实现会话好友列表的显示,话不多说,直接开撸。


会话好友列表的实现

1.监听回调事件

在开发中,我们可以通过监听回调事件的方式被动获取会话变更,以及通过api主动获取会话缓存数据,主动获取的是sdk底层缓存的会话列表数据,而回调的则是最新的,一般而言回调的时效性高于api。

主动获取会话列表:

getConversationList () {
    let{ data } = await this.$txim.getConversationList(this.nextSeq, 999)
    this.nextSeq = data.nextSeq
    data.conversationList = data.conversationList || data.conversations
    let conversationList = data.conversationList.sort((a,b) => b.lastMessage.timestamp - a.lastMessage.timestamp)
    this.conversationList = conversationList
}

监听会话消息变更:

// 初始化会话列表并且监听会话列表变化
this.$txim.$on('onNewConversation', this.onConversationHandler)
this.$txim.$on('onConversationChanged', this.onConversationHandler)

回调事件处理:

async onConversationHandler ({ data }) {
    // 这里的data是会话变更的列表,需要判断是新增还是变更(通过item.conversationID判断)
    for (let item of data) {
        let index = this.conversationList.findIndex(R => R.conversationID === item.conversationID)
        if (index >= 0) {
            this.conversationList.splice(index, 1, item)
        } else {
            this.conversationList.push(item)
        }
    }
},

2.同步刷新已读

一般而言我们是在接收到数据的时候进行已读标记,因此我们需要监听消息事件,判断是否当前聊天人员从而刷新已读
事件监听:

// 监听新的消息
this.$txim.$on('onRecvC2CTextMessage', this.onRecvMessageHanlder) // 个人文本消息
this.$txim.$on('onRecvC2CCustomMessage', this.onRecvMessageHanlder) // 个人高级消息
this.$txim.$on('onRecvGroupTextMessage', this.onRecvMessageHanlder) // 群组文本消息
this.$txim.$on('onRecvGroupCustomMessage', this.onRecvMessageHanlder) // 群组高级消息
this.$txim.$on('onRecvNewMessage', this.onRecvMessageHanlder) // 普通消息(非高级)

回调事件处理:

async onRecvMessageHanlder({ data }) {
    let isC2C = !!(data.sender.userID || data.sender)
    let sender = data.sender.userID || data.sender.groupID
    if (this.currentChatId == sender) {
        isC2C ? this.$txim.markC2CMessageAsRead(sender)
              : this.$txim.markGroupMessageAsRead(sender)
    }
}

3.删除会话消息

有显示有新增,那也就对应的有删除本地会话消息,删除本地会话消息我们要注意一点,删除之后只是本地聊天消息消失,云端依然存在,开发者可以自行在腾讯云后台配置历史记录天数。

doDeleteItem (item) {
    // 这里的item是通过界面回调的
    let index = this.conversationList.findIndex(R => R.conversationID == item.conversationID)
    this.$txim.deleteConversation(item.conversationID)
    this.conversationList.splice(index, 1)
}

项目开源地址及交流群

项目成品效果查看:请点击项目引言
项目开源地址:https://gitee.com/ckong/Zhimi...
Uniapp开发交流群:755910061


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK