Receive Push Notifications on Added Firebase Database
in my IOS app, I have Firebase installed. I can read, write and delete data. I also have Push Notifications setup and getting them from Firebase console.
What I didn't get to work is get Push Notification when I add new data to my Firebase database.
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
}
I am trying to subscribe to one of my database nodes, but I am not getting Push Notification when something changes
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 new
UserDefaults.standard.set(deviceTokenString, forKey: "PushDeviceTokenString")
}
+3
Peter Sypek
source
to share
1 answer
After i have set firebase functions in my project according to firebase manual.
All you had to do was create and deploy a server-side function that catches the event and performs the required function.
//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);
});
}
});
});
+1
Peter Sypek
source
to share