微信小程序接入騰訊雲IM即時通訊(在微信小程序底部設置消息未讀總數)
1.先看小程序api文檔:
- wx.setTabBarBadge(OBJECT)
- wx.removeTabBarBadge(OBJECT)
- 這兩個api對消息數量進行顯示隱藏** :https://developers.weixin.qq.com/miniprogram/dev/api/ui-tabbar.html#wxsettabbarbadgeobject
首先使用本地存儲,在app.js裏面做定義和判斷
if (wx.getStorageSync('unread') > 0 ){//消息數大於0才顯示,否則隱藏
wx.setTabBarBadge({
index: 1,
text: this.data.unread
})
}else{
wx.removeTabBarBadge({
index:1,
text: ''
})
}
完整代碼
//監聽新消息(私聊(包括普通消息、全員推送消息),普通羣(非直播聊天室)消息)事件
//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()
}
//更新消息未讀數
function getUnread(){
var sess= {};
var unread = 0 ;
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
})
//統計未讀消息數量顯示在底部欄
unread = that.data.contactList.reduce(function(prev,cur){
return cur.UnreadMsgCount + prev
},0)
// 獲取最新的會話消息
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
})
})
}
}
//設置消息未讀數量總數
unread = JSON.stringify(unread)
wx.setStorageSync('unread', unread)
app.data.unread = unread
if (unread != '0') {
wx.setTabBarBadge({
index: 1,
text:unread
})
} else {
wx.removeTabBarBadge({
index: 1
})
}
}
這段代碼寫在監聽新消息onMsgNotify事件裏面的更新未讀數時間裏面getUnread()
思路是每次獲取到新消息然後把會話列表所有的未讀消息數相加得出總數
這裏注意一下這個參數是個string類型的
//統計未讀消息數量顯示在底部欄
unread = that.data.contactList.reduce(function(prev,cur){
return cur.UnreadMsgCount + prev
},0)
//設置消息未讀數量總數
unread = JSON.stringify(unread)
wx.setStorageSync('unread', unread)
app.data.unread = unread
if (unread != '0') {
wx.setTabBarBadge({
index: 1,
text:unread
})
} else {
wx.removeTabBarBadge({
index: 1
})
}
有問題可以留言或者提問