1、首先可以使用unipush,这个没啥说的,根据官方配置走,勾上配置,以及添加对应SDK文件,然后在DCLOUD平台里配置下对应的appid和密钥,之后在app.vue文件中添加监听
plus.push.addEventListener(
'receive',
function (msg) {
plus.push.createMessage(msg.content, msg.payload, {
title: msg.title,
});
},
false,
);
plus.push.addEventListener(
'click',
function (msg) {
//xxxx
},
false,
);
或者说在首页tabbar文件里去添加这种也是可以的
2、使用个推平台
那么此时和个推对接交给原生去做了,配置不同厂商的规则等,uniapp端只需要接收以及主动获取数据
其实一般选择uni.push来实现推送功能即可,但是遇到使用个推平台的,并且uniapp应用是通过套原生壳子来打包,那么你做为前端可能会遇到和我一样的问题
如何分别和Android iOS两端实现内容交互
uni提供的供我们主动去跟原生获取信息参数的方式可以通过下面这种方式获取
let package = uni.requireNativePlugin("xx")//xx为包名
package.fun((res)=>{
console.log('res',res)//获取原生数据
})
我们可以通过这种方式获取对应的设备cid,然后让后端去交给运营存下cid;
实际代码如下
const pushPlugin = uni.requireNativePlugin('PushModule'); // 获取原生插件实例,名称要和注册时一致
if(pushPlugin){
pushPlugin.getPushCid((cid) => {
if(cid){
const { platform } = uni.getSystemInfoSync();
if (phone && !this.initedPush) {
uni.setStorageSync('push', true);
this.initedPush = true
try {
changeCid({ phone, cid, platform })
} catch (error) {
uni.showToast({
title: 'cid绑定失败',
icon: 'none',
duration: 2000,
});
console.log(error, 'changeCid error')
}
}
return;
}else{
uni.showToast({
title: '获取cid失败',
icon: 'none',
duration: 2000,
});
return;
}
});
//用uniapp弹框展示cid
}
之后的话,就需要关注如何被动监听原生传到uniapp的消息,
Android:
这里就直接可以参考这位佬的帖子:Android传递给uniapp
实际我这边实现是放在app.vue文件的onShow钩子里去实现的:
if(uni.getSystemInfoSync().platform == 'android'){
this.myEventManager = plus.android.importClass("uni.UNI990A59C.PushManager");
this.eventManager = this.myEventManager.getPushManager();
//新建监听器
this.myListener = plus.android.implements("uni.UNI990A59C.PushListener", {
//通知栏点击调用
"onClick":function(event){
//导入类
plus.android.importClass(event);
if(event.getMsgType() == '1'){
//dosomething
}
},
//实时收到消息调用
"onReceive":function(event){
//导入类
plus.android.importClass(event);
//通知页面获取消息
uni.$emit('showMsgModal',event)
}
});
this.eventManager.addListener(this.myListener);
}
uniapp这块就是这样实现
iOS:
网上没找到对应的一些交互方式,
貌似要么纯H5取webview的定义在window对象上的方法,试过貌似行不通
采用的方案是我这边继续导入原生的资源包,也是放在app.vue中在一开始就调,objectC貌似可以保存调用状态。
不同的type区分触发不同场景事件
if(uni.getSystemInfoSync().platform == 'ios'){
// plus.globalData
const pushPlugin = uni.requireNativePlugin('PushModule');
// 注册点击推送消息的回调
pushPlugin.getPushMessage((result) => {
// 处理点击推送消息后的逻辑,例如跳转到对应的详情页
// 这里假设推送消息携带了一些参数,比如taskId,你需要根据实际传递的参数名来获取
if(result){
if(result.type == 'onReceive'){
uni.$emit('showMsgModal',result)
}
if(result.type == 'onClick'){
if(result.msgType == '1'){
//dosomething
}
}
}
});
}