Xamarin/C# 数据变更通知

Notification on change of data in Xamarin/C#

你好,我已经根据这个答案实现了一个方法: How to get notification in xamarin forms on firebase data change? 但我无法让它正常工作。

这是我的代码:

      void DoFirebaseObserve()
      {
            var firebase = new FirebaseClient(Constants.FirebaseProjectUrl);
            firebase.Child("RegisterUserTable").AsObservable<RegisterUser>().Subscribe(obs =>
            {
                switch (obs.EventType)
                {
                    case Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate:
                        Console.WriteLine("InsertOrUpdate");
                        break;
                    case Firebase.Database.Streaming.FirebaseEventType.Delete:
                        Console.WriteLine("Delete");
                        break;
                    default:
                        break;
                }
            });

       }

我在应用程序主页的 OnAppearing 方法中调用此代码。我试过使用和不使用 while (true) {} 条件。

当我在 firebase 中添加、更新或删除记录时,我的应用程序没有任何反应。永远不会调用写入行。

如有任何帮助,我们将不胜感激。谢谢

所以我想出了如何通过在 Firebase 控制台中使用 Google Cloud Functions 来实现它。

第 1 步。在您的 .Net 代码中设置 FCM

按照本教程进行操作: https://docs.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=macos

从该设备获得 FCM 令牌后,您可以将其添加到实时数据库中(我自己在 firebase 控制台中手动执行此操作以进行测试)。

步骤 2. 设置云功能

按照本教程进行操作: https://www.youtube.com/watch?v=bpI3Bbhlcas&t=1104s&ab_channel=uNicoDev

步骤 3. 创建发送消息的函数

您可以在云函数中使用此 node.js 代码发送最多 500 台设备:

// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
  'YOUR_REGISTRATION_TOKEN_1',
  // …
  'YOUR_REGISTRATION_TOKEN_N',
];

const message = {
  data: {score: '850', time: '2:45'},
  tokens: registrationTokens,
};

admin.messaging().sendMulticast(message)
  .then((response) => {
    console.log(response.successCount + ' messages were sent successfully');
  });

来源:https://firebase.google.com/docs/cloud-messaging/send-message#node.js_1

代码示例

我的一些代码可以帮助您了解如何着手做这样的事情。不能保证这是最佳方法,但它有效。

    const reference = "JourneyTbl/{journeyId}";

// newJourneyAdded | listener method | Send push notif when new journey created:
exports.newJourneyAdded = functions.database.ref(reference)
    .onCreate((event, context) => {
      // where fcm tokens are stored:
      const refNotifications = "NotificationTbl";
      // get ref to RegNotTable:
      const refFcm = admin.database().ref(refNotifications);
      // array to hold all fcms from table:
      const allFcms = [];
      // get value of "NotificationTbl":
      refFcm.on("value", (snapshot) => {
        // check if there's any children:
        if (snapshot.hasChildren()) {
          // loop through children:
          snapshot.forEach((element) => {
            // stringify the data:
            const asString = JSON.stringify(element);
            // parse that as a JSON object:
            const asJson = JSON.parse(asString);
            // add fcm token to array:
            allFcms.push(asJson.fcm);
          });
        }

        // if array contains something:
        if (allFcms.length > 0) {
          // construct message to send:
          const msg = {
            notification: {
              title: "Notification Title goes here",
              body: "Notification Body goes here ",
            },
            tokens: allFcms, // pass the tokens
          };
          // send that message:
          admin.messaging().sendMulticast(msg)
              .then((response) => {
                console.log(response.successCount + " mgs were sent sfly");
              });
        } else {
          console.log("No devices in FCM tokens list");
        }
      });
      return "ok";
    });