在Firebase数据库中添加了推送通知

时间:2017-07-17 18:10:58

标签: 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")
}

1 个答案:

答案 0 :(得分:2)

根据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);
            });
        }
    });
});