在线存储FCM令牌 [英] Storing FCM tokens online

查看:155
本文介绍了在线存储FCM令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个iOS应用程序,该应用程序调用Firebase云功能来存储FCM令牌,以便以后发送通知时使用.问题在于它不起作用.

I am working with an iOS app which calls an Firebase cloud function, to store FCM tokens, for later use when sending notifications. The problem is that it does not work.

我正在使用Cloud Firestore数据库.

I am using a Cloud Firestore database.

调用函数时,这就是我要发生的事情.该功能对照数据库检查参数.如果在数据库中已经找到提供的参数中的数据,则什么也不会发生. 如果找不到,则应将其添加到数据库中.

When the function is called, here is what I want to happen. The function checks the parameters against a database. If the data in the provided parameter is already found in the DB then nothing should happen. If it is not found, then it should be added to the DB.

我的云功能代码如下.如果有人可以帮助我找到确切的问题,我将感到非常高兴.

My cloud function code is below. I would be glad if someone could help me find the precise issue.

exports.addNewElement = functions.https.onCall((data, context) => {
  console.log('--addNewElement-- has been called with:\n' + data.fcmToken + '\n!!');
  var collectionRef = db.collection("THE_COLLECTION");

  // Create a query against the collection.
  var query = collectionRef.where("fcmToken", "==", data.fcmToken);
  query.get().then(function(doc) {
    if (doc.exists) { // We should do nothing.
        console.log("Document data:", doc.data());
    } else { // We should add the new element.
        // doc.data() will be undefined in this case
        console.log("No such document!");
        collectionRef.add({"fcmToken": fcmToken})
    }
  }).catch(function(error) {
    console.log("Error getting document:", error);
  });
});

我可以想象处理FCM令牌的其他方向. 有什么推荐的方法可以用作最佳实践吗?

I could imagine other directions to handle FCM tokens. Is there any recommend way to use as best practice?

推荐答案

我采取了另一种方法.我有一个离子应用程序,并且该应用程序已在FCM中注册(我们拥有FCM令牌),然后直接从该应用程序将该令牌添加到设备"集合中.这样,用户可以登录到不止一台设备,并且我们将获得每个设备的令牌,从而使我们能够将消息发送到每个设备.如果要向用户发送消息,请查询设备集合以获取该uid,以获取该用户的所有令牌

I take a bit of a different approach. I have an ionic app and after the app has registered with FCM (we have FCM token), I add the token to a 'devices' collection straight from the app. This way, a user can log in to more then one device and we will have the token for each device enabling us to send the message to each device. If you want to send a message to a user, you query the devices collection for that uid to get all the tokens for that user

保存令牌:

    private saveTokenToFirestore(person: Person, token) {
        if (!token) return;
        const devicesRef = this.afs.collection('devices')

        const docData = { 
          token,
          userId: person.id,
        }

        return devicesRef.doc(token).set(docData)
      }

其中person.id是Firebase uid.

where person.id is the firebase uid.

然后我使用firebase函数监视某些节点,以弄清楚何时发送FCM消息.

I then use firebase functions to monitor some nodes to figure out when to send FCM messages.

例如我们有以人为成员的团队,他们可以彼此聊天.当一个人向团队发送消息时,每个团队成员(发件人本人除外)都需要获得通知.

e.g. we have teams with persons as members and they can chat to each other. When a person sends a message to a team, each team member (except the sender himself) needs to get a notification.

向发件人本人以外的所有成员发送通知:

exports.chatMessageOnCreateSendFcm = functions.firestore
    .document('chatGroups/{teamId}/messages/{messageId}')
    .onCreate(async (snap, context) => {
        const data = snap.data();
        const teamId = context.params.teamId;
        const name = data.pName;
        const message = data.msg;
        const userId = data.pId;

        // Notification content
        const payload = {
            notification: {
                title: name,
                body: message,
            }
        }

        const db = admin.firestore();

        // get the team (chatGroup)
        const teamRef = db.collection('teams').doc(teamId);
        const teamSnapshot = await teamRef.get();
        const team = teamSnapshot.data();
        const devicesRef = db.collection('devices');
        const queries: Promise<FirebaseFirestore.QuerySnapshot>[] = team.members
            .filter(f => f.id !== userId)
            .map(member => {
                return devicesRef.where('userId', '==', member.id).get();
            });

        return Promise.all(queries)
            .then((querySnapshots) => {
                const tokens = [];
                querySnapshots.forEach(snapShot => {
                    if (snapShot) {
                        snapShot.docs.forEach(doc => {
                            if (doc) {
                                const token = doc.data().token;
                                if (token) {
                                    tokens.push(token);
                                }
                            }
                        })
                    }
                });

                if (tokens.length === 0) {
                    return Promise.resolve(null);
                } else {
                    return admin.messaging().sendToDevice(tokens, payload);
                }
            })
            .catch(err => {
                console.error(err);
                return Promise.resolve(null);
            });
    });

您可以根据自己的需要修改以上内容.希望对您有帮助

You can modify the above to suit your needs. Hope it helps

这篇关于在线存储FCM令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆