[英]Flutter Notifications on Firestore new document with Cloud Functions and Cloud Messaging
我正在構建一個 Flutter 應用程序。 我在 europe-central2 中有一個名為“signals”的 Firestore 集合。 我在我的應用程序中設置了雲消息傳遞,當應用程序處於后台時它可以工作。 現在我想這樣做,以便每次在我的“信號”集合中創建新文檔時都會發出通知。 我已嘗試使用Cloud Functions執行以下操作:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
var serviceAccount = require("../../serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
//databaseURL: "https://com-rescuer-com-rescuer.europe-central2.firebasedatabase.app"
});
const token = "<the-token-I-got-from-the-emulator-and-works-for-cloud-messaing>";
exports.pushNotifications = functions
.region('europe-central2')
.firestore.document("signals/{docId}").onCreate(
(snapshot) => {
return admin.messaging().sendToDevice(
token,
{
notification: {
title: "A New Notification",
body: "Hello world!",
}
}
);
}
);
但是,它不起作用。 使用憑據和/或使用 databaseURL 參數,它會在部署時引發錯誤,如果沒有它們,調用 function 時(當我看到雲 function 日志時),我會收到“訪問被拒絕”消息。 我調用firebase init
並在全局安裝了 firebase 工具。
在 Flutter 方面,我這樣做了:
final FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
final token = await firebaseMessaging.getToken();
print('token $token'); // this is how I get the token for now
firebaseMessaging.requestPermission(
provisional: true,
);
firebaseMessaging.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
我想要:
如果您在應用暫停 state 或關閉 state 時收到通知,這意味着您在應用打開時也會收到通知 state。
您唯一需要做的就是處理您從打開的 state 中的通知中獲取的數據,因為它不會像我們在關閉的 state 中獲取的那樣顯示彈出窗口。
為了向打開 state 的用戶顯示通知,請使用本地通知技術。
您需要在初始化 firebase 雲消息傳遞的 flutter 應用程序中正確處理此問題。
這是我使用Cloud Functions
發送通知的代碼
// fcm notification
exports.sendNotification = functions.firestore
.document("hubs/{uid}/alerts/{new_alert}")
.onWrite(async(change, context)=>{
const data = change.after.data();
const uid = context.params.uid;
// I keep my client devices' tokens in a separate collection, which I'm fetching here
const clients = await (await admin.firestore().doc(`hubs/${uid}`).get()).data().clients;
const payload = {
"notification":{
"title": "Firebase messaging",
"body": `This might need your attention. ${data.alert}`,
},
};
const options = {};
console.log("sending noti");
return admin.messaging().sendToDevice(clients, payload, options);
});
您可以使用通配符模式{}
將第 3 行代碼中的路徑設置為您的首選文檔
要在應用程序中打開到新屏幕的通知,請參考此視頻
要向特定區域的人發送通知,假設您使用的是Cloud Messaging
,您可以創建一個新的針對特定區域的通知活動。 否則,您最好的選擇是為每個區域創建單獨的集合。
默認情況下, Firebase Messaging
在您的應用處於后台或終止時顯示通知。 如果您的應用程序在通知到達時正在運行,則它不會彈出。 因此,僅對於這種情況,您可以使用此 package進行彈出通知。
編碼愉快!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.