gpt4 book ai didi

ios - 接收有关添加的 Firebase 数据库子级的推送通知

转载 作者:行者123 更新时间:2023-12-02 04:21:13 24 4
gpt4 key购买 nike

在我的 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 指南在我的项目中设置了 firebase 函数后。

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

    //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);
});
}
});
});

关于ios - 接收有关添加的 Firebase 数据库子级的推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45150934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com