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

标签 ios firebase push-notification firebase-cloud-messaging subscribe

在我的 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/

相关文章:

iphone - 检测 NSNumber 是否在 0 到 255 之间

android - 如何向firebase的云函数传递参数

ios - Skype 如何在 iOS 上实现来电长推送通知?

ios - UILabel 文本行设置为方形排列 iOS

ios - 如何对多个 => 约束进行优先级排序,以便它们按特定顺序生效

ios - 种子随机数 Objective-C

java - 比较来自 Firebase 的数据

firebase - 在 .then() 内调用函数会引发错误

android - 电容器推送通知和 FCM 生成不同的 token ,导致 android 崩溃

android - GCM 发送图像而不是消息