通过 FCM 发送数据消息



当有人关注用户时,我正在尝试通过iOS应用程序上的Firebase Cloud Messaging 向用户发送通知,我已经在服务器上设置并部署了javascript,这似乎很成功:

'我们有一个新的追随者UID:8dUMfYX9NibJDgOm3qdTcvtVO523,用于用户:FVa0Gy5KlVMLvipoWRRqsZ1CluF3'

在控制台日志中出现,这些是正确的 UID,但它也指出:

"没有要发送到的通知令牌"。

我的想法是令牌没有链接到身份验证帐户,但我不确定如何或在什么时候应该。我还应该注意,我已经连接到应用程序委托中的 fcm,并使用以下方法收到了令牌:

InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instange ID: (error)")
}
else {
print("FCM Token = (String(describing: result?.token))")
print("Remote instance ID token: (result!.token)")
//     self.instanceIDTokenMessage.text  = "Remote InstanceID token: (result.token)"
}
}

这是JavaScript:

'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
/**
* Triggers when a user gets a new follower and sends a notification.
*
* Followers add a flag to `/followers/{followedUid}/{followerUid}`.
* Users save their device notification tokens to `/users/{followedUid}/notificationTokens/{notificationToken}`.
*/
exports.sendFollowerNotification = functions.database.ref('/users/{followerUid}/following/{followedUid}')
.onWrite(async (change, context) => {
const followerUid = context.params.followerUid;
const followedUid = context.params.followedUid;
// If un-follow we exit the function.
if (!change.after.val()) {
return console.log('User ', followerUid, 'un-followed user', followedUid);
}
console.log('We have a new follower UID:', followerUid, 'for user:', followedUid);
// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database()
.ref(`/users/${followedUid}/notificationTokens`).once('value');
// Get the follower profile.
const getFollowerProfilePromise = admin.auth().getUser(followerUid);
// The snapshot to the user's tokens.
let tokensSnapshot;
// The array containing all the user's tokens.
let tokens;
const results = await Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]);
tokensSnapshot = results[0];
const follower = results[1];
// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
console.log('Fetched follower profile', follower);
// Notification details.
const payload = {
notification: {
title: 'You have a new follower!',
body: `${followerUid.name} is now following you.`
}
};
// Listing all tokens as an array.
tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
// 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的部分说:

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

需要以以下格式连接到数据库:

users:{
$user_id:{
notificationTokens:{
$token: true
}
}
}

为了访问令牌,因为可以有多个用户登录的实例,我之前已将密钥"notificationTokens"的值设置为令牌 - 这就是它不起作用的原因。

相关内容

  • 没有找到相关文章

最新更新