微信小程序接入騰訊雲IM即時通訊(會話列表之未讀消息,顯示最新一條消息開發步驟)
1.未讀消息思路
首先,獲取未讀消息第一步就是要先能接收到對方發送的信息,也就是要在官方api中給的監聽新消息事件做處理。先看下圖需要做的功能點
- 接收到對方發過來的新消息之後獲取消息的未讀計數;
js代碼
1.先獲取未讀的消息計數,獲取會話列表最新的一條消息
//獲取消息未讀數並更新到會話列表
function getUnread(){
var sess= {};
var sessMap = webim.MsgStore.sessMap();
if (that.data.contactList) {//這裏判斷是否存在會話列表,或者在會話列表的頁面
// 更新消息的未讀數
for (var i in sessMap) {
sess = sessMap[i];
var contactList = that.data.contactList.map((item, index) => {
if (item.To_Account == sess.id()) {
item.UnreadMsgCount = sess.unread()
}
return item;
})
//先把未讀數賦值
that.setData({
contactList: contactList
})
// 獲取最新的會話消息(把最新的一條賦值到會話列表)
webim.getRecentContactList({
'Count': 10 //最近的會話數 ,最大爲 100
}, function (resp) {
var MsgShow = resp.SessionItem.filter((item, index) => {
if (item.To_Account == sess.id()) return item;
})
var contactList = that.data.contactList.map((item, index) => {
if (item.To_Account == sess.id()) {
// 獲取最新消息
if (MsgShow[0].MsgShow == '[其他]'){
MsgShow[0].MsgShow = '[房源信息]'
}
item.MsgShow = MsgShow[0].MsgShow
}
return item;
})
that.setData({
contactList: contactList
})
})
}
}
}
2.在接收到新消息事件中調用這個方法getUnread()這個方法
//獲取消息未讀數並更新到會話列表
//監聽新消息(私聊(包括普通消息、全員推送消息),普通羣(非直播聊天室)消息)事件
//newMsgList 爲新消息數組,結構爲[Msg]
function onMsgNotify(newMsgList) {
var newMsg;
//獲取所有聊天會話
for (var j in newMsgList) {//遍歷新消息
newMsg = newMsgList[j];
if (newMsg.getSession().id() == id) {//爲當前聊天對象的消息
selSess = newMsg.getSession();
handlderMsg(newMsg, false);
currentMsgsArray = currentMsgsArray.map((item, index) => {
if (!item.isSelfSend) {
item.avatar = myAvatar
} else {
item.avatar = friendAvatar
}
return item;
})
var myMessages = that.setDatas(currentMsgsArray);
that.setData({
myMessages: myMessages,
})
setTimeout(function () {
if (that.data.is_chat){
that.pageScrollToBottom()
}
}, 100)
}
}
getUnread()
}