1、接入im
npm install @tencentcloud/chat
// 发送图片、文件等消息需要腾讯云即时通信 IM 上传插件
npm install tim-upload-plugin --save
// 拦截或替换敏感词需要本地审核插件
npm install tim-profanity-filter-plugin --save
2、在main.js上引入并且导入全局
import TIM from 'tim-js-sdk'
let options = {
SDKAppID: xxxxxxxxxx // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
};
// 创建 SDK 实例,`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
Vue.prototype.tim = TIM.create(options); // SDK 实例通常用 tim 表示
3、登录个人实验好几次在app.vue 和 登录的时候都加上
if (uni.getStorageSync('token') != '') {
// 自己封装的请求接口获取个人用户id
request.http('xxxxxxxx').then(res => {
console.log(res);
uni.setStorageSync('usera', res.data);
// 请求后端获取usersig
uni.request({
url: `${config.serverUrl}/xxxxx?userId=${res.data.userId}`,
method: 'POST',
success: function(resc) {
console.log(resc);
let promise = tim.login({
userID: res.data.userId,
userSig: resc.data.data
});
promise.then(function(imResponse) {
console.log(imResponse.data); // 登录成功
if (imResponse.data.repeatLogin === true) {
// 标识帐号已登录,本次登录操作为重复登录。v2.5.1 起支持
console.log(imResponse.data.errorInfo);
}
}).catch(function(imError) {
console.warn('login error:', imError); // 登录失败的相关信息
console.log(22);
});
}
})
})
}
4发送消息这个和后端商量用什么作为im的标识id我用的是userid简单
handleSend() {
//如果消息不为空
var that = this
console.log(that.chatMsg);
if (!that.chatMsg || !/^\s+$/.test(that.chatMsg)) {
let message = tim.createTextMessage({
to: that.userId,
conversationType: TIM.TYPES.CONV_C2C,
// 消息优先级,用于群聊(v2.4.2起支持)。如果某个群的消息超过了频率限制,后台会优先下发高优先级的消息,详细请参考:https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
// 支持的枚举值:TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL(默认), TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
text: that.chatMsg
},
// v2.20.0起支持C2C消息已读回执功能,如果您发消息需要已读回执,需购买旗舰版套餐,并且创建消息时将 needReadReceipt 设置为 true
needReadReceipt: true
// 消息自定义数据(云端保存,会发送到对端,程序卸载重装后还能拉取到,v2.10.2起支持)
// cloudCustomData: 'your cloud custom data'
});
tim.sendMessage(message, {
// 如果接收方不在线,则消息将存入漫游,且进行离线推送(在接收方 App 退后台或者进程被 kill 的情况下)。
// 接入侧可自定义离线推送的标题及内容
offlinePushInfo: {
title: '111', // 离线推送标题
description: '222', // 离线推送内容
androidOPPOChannelID: 'realme', // 离线推送设置 OPPO 手机 8.0 系统及以上的渠道 ID
extension: JSON.stringify({
entity: { // entity 中的内容可自定义
nick: '哈哈哈',
userID: 'user1',
}
})
}
})
// 2. 发送消息
let promise = tim.sendMessage(message);
promise.then(function(imResponse) {
// 发送成功
console.log(imResponse);
that.conversationID = imResponse.data.message.conversationID
that.chatMsg = ''
if (imResponse.data.message.from == that.userId) {
imResponse.data.message.isyou = 0
} else {
imResponse.data.message.isyou = 1
}
imResponse.data.message.times = formatDate((imResponse.data.message.time) * 1000)
that.content.push(imResponse.data.message)
}).catch(function(imError) {
// 发送失败
console.warn('sendMessage error:', imError);
});
that.scrollToBottom()
} else {
this.$modal.showToast('不能发送空白消息')
}
},