如何为收到的每个推送通知增加应用程序徽章编号

问题描述 投票:0回答:2

我正在使用firebase云功能发送用户推送通知。我不太了解JS,但我希望能够通过通知有效负载自动增加应用程序徽章编号,并为每个收到的通知增加1。这就是我现在拥有的。我已经阅读了firebase的文档,但我认为我没有足够的JS理解来弄清楚他们在描述什么。

exports.sendPushNotificationLikes = functions.database.ref('/friend-like-push-notifications/{userId}/{postId}/{likerId}').onWrite(event => {
const userUid = event.params.userId;
const postUid = event.params.postId;
const likerUid = event.params.likerId;
if (!event.data.val()) {
    return;
}

// const likerProfile = admin.database().ref(`/users/${likerUid}/profile/`).once('value');

const getDeviceTokensPromise = admin.database().ref(`/users/${userUid}/fcmToken`).once('value');

// Get the follower profile.
const getLikerProfilePromise = admin.auth().getUser(likerUid);

return Promise.all([getDeviceTokensPromise, getLikerProfilePromise]).then(results => {
    const tokensSnapshot = results[0];
    const user = results[1];

    if (!tokensSnapshot.hasChildren()) {
        return console.log('There are no notification tokens to send to.');
    }

    const payload = {
        notification: {
            title: 'New Like!',
            body: '${user.username} liked your post!',
            sound: 'default',
            badge: += 1.toString()
       }
    };

    const tokens = Object.keys(tokensSnapshot.val());

    // Send notifications to all tokens.
    return admin.messaging().sendToDevice(tokens, payload).then(response => {
            // For each message check if there was an error.
            const tokensToRemove = [];
        response.results.forEach((result, index) => {
            const error = result.error;
        if (error) {
            console.error('Failure sending notification to', tokens[index], error);
            // Cleanup the tokens who are not registered anymore.
            if (error.code === 'messaging/invalid-registration-token' ||
                error.code === 'messaging/registration-token-not-registered') {
                tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
                }
             }
        });
        return Promise.all(tokensToRemove);
    });
});

});

在此先感谢您的帮助

javascript apple-push-notifications google-cloud-functions
2个回答
1
投票

我猜这就是问题所在:

const payload = {
   notification: {
       title: 'New Like!',
       body: '${user.username} liked your post!',
       sound: 'default',
       badge: += 1.toString()
   }
};

假设您的架构中有可用的通知计数属性,请说notificationCount然后您可以这样做:

const payload = {
   notification: {
       title: 'New Like!',
       body: `${user.username} liked your post!`,
       sound: 'default',
       badge: Number(notificationCount++) // => notificationCount + 1
   }
};

同样在这个body: '${user.username} liked your post!',这将被保存为"user.username like your post!"。这不是你想要的行为,你应该做的是:

body: `${user.username} liked your post!`

0
投票

假设这是有问题的一行:

 badge: += 1.toString()

小心类型转换假设。添加“1”+“1”将为您提供“11”,而不是“2”。为什么不尝试类似的东西:

badge: `${targetUser.notificationCount + 1}`

这假设notificationCount是模式中的一个键,并且它被键入为字符串。您将需要在某个地方保留目标用户的通知计数,以便在新通知进入时可以递增。它也可以是整数,然后不需要字符串插值,即:

badge: targetUser.notificationCount + 1

另外,请注意,此处的字符串插值需要用反引号而不是单引号括起来,即:

body: `${user.username} liked your post!`

我无法分析数据库中的交互是如何映射的。此方法需要持久化并更新目标用户的通知计数。

© www.soinside.com 2019 - 2024. All rights reserved.