注:本文章参考多篇文章组成,
1.申请SDKAppID 并 引入腾讯im文档 TUIKit组件
组件地址:https://cloud.tencent.com/document/product/269/64507
哪找教程引入就行,开发什么端看什么端文档
npm install tim-wx-sdk@2.15.0--save
npm install cos-wx-sdk-v5@0.7.11--save
----------------------------------------------------------
import TIM from 'tim-wx-sdk';
import COS from "cos-wx-sdk-v5";
import logger from './utils/logger'; // app.js
import { genTestUserSig } from './debug/GenerateTestUserSig.js'
2.im登录
在app.vue文件下onLaunch周期里面:
/// userInfo 为判断用户是否登录
if( userInfo != '' || userInfo != undefined ) {
if( uni.getStorageSync('zuserInfo').role == 1 || uni.getStorageSync('zuserInfo').role == 2 ) {
// 连接im
// 如果您已经接入 tim ,请将 uni.tim 修改为 uni.$TUIKit。
uni.$TUIKit = TIM.create({
SDKAppID: ' ' // 填写你申请的AppID
});
uni.$TUIKit.registerPlugin({
'cos-wx-sdk': COS
});
uni.$resetLoginData = this.resetLoginData(userInfo)
uni.$TUIKitTIM = TIM;
uni.$TUIKitEvent = TIM.EVENT;
uni.$TUIKitVersion = TIM.VERSION;
uni.$TUIKitTypes = TIM.TYPES; // 监听系统级事件
uni.$TUIKit.on(uni.$TUIKitEvent.SDK_NOT_READY, this.onSdkNotReady);
uni.$TUIKit.on(uni.$TUIKitEvent.KICKED_OUT, this.onKickedOut);
uni.$TUIKit.on(uni.$TUIKitEvent.ERROR, this.onTIMError);
uni.$TUIKit.on(uni.$TUIKitEvent.NET_STATE_CHANGE, this.onNetStateChange);
uni.$TUIKit.on(uni.$TUIKitEvent.SDK_RELOAD, this.onSDKReload);
uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady);
}
}
// TODO:
resetLoginData(info) {
let _this = this
this.globalData.expiresIn = '';
this.globalData.sessionID = '';
this.globalData.userInfoIm = {
userID: info.userId,
userSig: info.txSig,
token: info.token,
phone: info.phone
};
this.globalData.userProfile = null;
uni.$TUIKit.login({userID: info.userId.toString(), userSig: info.txSig.toString()})
.then(function(imResponse) {
// console.log(imResponse.data); // 登录成功
// _this.getUpdateMyProfile()
if (imResponse.data.repeatLogin === true) {
// 标识帐号已登录,本次登录操作为重复登录。v2.5.1 起支持
// console.log(imResponse.data.errorInfo);
}
})
.catch(function(imError) {
console.warn('login error:', imError); // 登录失败的相关信息
});
},
onTIMError() {},
onNetStateChange() {},
onSDKReload() {},
onSDKReady(event) {
let _this = this
_this.getUpdateMyProfile()
_this.getImUnread()
},
onSdkNotReady() {
this.getImLogin()
},
onKickedOut() {
uni.showToast({
title: '您被踢下线',
icon: 'error'
});
let userinfo = ''
uni.setStorageSync('zuserInfo', userinfo)
setTimeout(()=>{
uni.redirectTo({
url: '/pages/login/login'
});
},2000)
// uni.navigateTo({
// url: './pages/TUI-Login/login'
// });
},
3. 退出登录
logoutTim() {
uni.$TUIKit.logout()
},
4.点击跳转登录(c2c为聊天室类型,楼主只用单聊,所以写死c2c)
uni.navigateTo({
url: '/pages/TUI-Chat/chat?conversationID=C2C' + this.info.user_id
});
5.获取未读消息,
getImUnread() {
uni.$TUIKit.getConversationList().then(res => {
// console.log(res.data.conversationList)
for( let i of res.data.conversationList ) {
if( i.unreadCount != 0 ) {
uni.showTabBarRedDot({index:2})
return
}
}
}).catch(fail => {
// console.log(fail)
});
},