添加了在 Firebase 数据库上接收推送通知子项



在我的IOS应用程序中,我已经设置了Firebase。 我能够读取、写入和删除数据。 我还设置了推送通知并从 Firebase 控制台接收它们。

我没有开始工作的是在向Firebase数据库添加新数据时收到推送通知。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
// Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true       
//Device Token for Push
// iOS 10 support
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 7 support
else {
application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
}
return true
}

我尝试订阅我的一个数据库节点,但在发生更改时没有收到推送通知

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Convert token to string
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("APNs device token: (deviceTokenString)")
//Messaging.messaging().setAPNSToken(deviceToken, type: MessagingAPNSTokenType.sandbox)
Messaging.messaging().subscribe(toTopic: "/topics/news")
// Persist it in your backend in case it's new
UserDefaults.standard.set(deviceTokenString, forKey: "PushDeviceTokenString")
}

在我根据火力基地指南在我的项目中设置火力基地函数之后。

您所要做的就是创建和部署一个服务器端函数,该函数捕获事件并执行所需的功能。

//Firebase functions setup
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//register to onWrite event of my node news
exports.sendPushNotification = functions.database.ref('/news/{id}').onWrite(event => {
//get the snapshot of the written data
const snapshot = event.data;
//create a notofication
const payload = {
notification: {
title: snapshot.child("title").val(),
body: snapshot.child("message").val(),
badge: '1',
sound: 'default',
}
};
//send a notification to all fcmToken that are registered
//In my case the users device token are stored in a node called 'fcmToken'
//and all user of my app will receive the notification
return admin.database().ref('fcmToken').once('value').then(allToken => {
if (allToken.val()){
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payload).then(response => {
console.log("Successfully sent message:", response);
});
}
});
});

相关内容

  • 没有找到相关文章