如何使用Firebase云函数增加徽章计数

4

目前我的负载只发送了一个徽章计数,即使你收到多个通知,徽章计数的值也不会增加。

应该如何编写JavaScript代码?

我目前的代码:

const functions = require('firebase-functions');                   
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase);
exports.sendPushForHelp = 
functions.database.ref('/help/school/{id}').onWrite(event => {
   const payLoad = {
     notification: {
         title: 'Someone',
         body: 'needs help',
         badge: '1',
         sound: 'Intruder.mp3'
     }
   };
   return admin.database().ref('fcmToken').once('value').then(allToken => {
       if (allToken.val()) {
        const token = Object.keys(allToken.val());
        return admin.messaging().sendToDevice(token, payLoad).then(response => {

            });
        };
    });
});

你能不能只是创建一个增量整数,然后将常量payLoad中的badge值设置为它? - Surreal
你的意思是我应该在Xcode(Swift代码)中包含增量int。然后我应该在有效载荷中使用该变量。比如说badge:badgecount? - Lukayne
当然,我会在答案中快速撰写一篇文章。 - Surreal
非常抱歉回复这么多次,但是它还是不起作用。因为当您将该函数导出到Firebase云函数时,会出现错误。错误是:“badgeCount ++             ^^^^^^^^^^ SyntaxError:意外的标识符” - Lukayne
抱歉这段时间没有消息,我刚回到家,你解决了这个问题吗? - Surreal
显示剩余5条评论
1个回答

4
你可以在JS中存储badgeCount,并在每次调用时递增,或随机化或进行其他操作。
例如:
const functions = require('firebase-functions');                   
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase);
var badgeCount = 1;
exports.sendPushForHelp = 
functions.database.ref('/help/school/{id}').onWrite(event => {
   const payLoad = {
     notification: {
         title: 'Someone',
         body: 'needs help',
         badge: badgeCount.toString(),
         sound: 'Intruder.mp3'
     }
   };
   badgeCount++; //or whatever
   return admin.database().ref('fcmToken').once('value').then(allToken => {
       if (allToken.val()) {
        const token = Object.keys(allToken.val());
        return admin.messaging().sendToDevice(token, payLoad).then(response => {
          //here might be a good place to increment as well, only on success
            });
        };
    });
});

这不考虑打开应用或应用内的某些操作会清除徽章计数,对吧? - matador0227

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接