uniapp 使用 uni push 2.0 推送消息

因为之前使用uni push 1.0,开通账号和配置厂商就不写了。只说一点,配置厂商很重要,不然收不到离线推送的消息。那么就直接开始咯!!!

一、创建并关联云服务空间

1.创建云服务空间,右键项目【创建uniClound云开发环境】,然后选择运营商【腾讯云、阿里云】。

 

2.关联云服务空间,如图:右键【uniCloud】===>点击【关联云服务空间或项目】然后选择需要关联的云服务空间名称,点击关联。

 

 

 3.新建云函数,如图所示

 

 

 

 

4.在云函数中添加以下代码

 

'use strict';
const uniPush = uniCloud.getPushManager({appId:"__UNI__XXXXXX"})
exports.main = async (event) => {
const res = await uniPush.sendMessage({
"push_clientid": event.cids,
"title": event.title,
"content": event.content,
"payload": event.data,
"force_notification": true,
"request_id": event.request_id
})
return res;
};

 

 

二、调用云函数推送信息

 

 

function getId() {
let yy = new Date().getFullYear();
let mm = new Date().getMonth() + 1;
let dd = new Date().getDate();
let hh = new Date().getHours();
let mf =
new Date().getMinutes() < 10 ?
"0" + new Date().getMinutes() :
new Date().getMinutes();
let ss =
new Date().getSeconds() < 10 ?
"0" + new Date().getSeconds() :
new Date().getSeconds();
let Randnum = "";
for (var i = 0; i < 10; i++) {
Randnum += Math.floor(Math.random() * 10);
}
return "ID_" + yy + mm + dd + hh + mf + ss + Randnum;
}

function appPushInfo(cids, title, content, data) {
return new Promise((resolve) => {
const request_id = getId();
uniCloud.callFunction({
name: '云函数名称',
data: {
cids,
title,
content,
data,
request_id
}
}).then((res) => {
resolve(res.success)
}).catch(() => {
resolve(false);
})
});
}

#个人对推送信息的方法进行了封装,相信配置请看官网api uni-app官网 (dcloud.net.cn)

三、在应用生命周期【onShow】中添加以下代码

 

 

//启动推送事件监听
uni.onPushMessage((res) => {
console.log(res);
});

// #ifdef APP-PLUS 用于判断平台,如果你的只是app,可以省略。小程序也可以使用推送事件监听,但是现在还不支持离线推送,听说还在研发中,等研发好了再来更新。

根据监听的参数就可以做一些业务处理了。

到处结束。欢迎探讨!!!

posted @ 2022-08-08 20:17  天空中的那朵白云  阅读(11118)  评论(1)    收藏  举报