3
votes

in my IOS application i have set up Firebase. I'am able to read, write and delete data. I also have setup Push Notifications and receive them from Firebase console.

What i did not get to work is to receive 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 try to subscribe to one of my database nodes but i get no 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's new
    UserDefaults.standard.set(deviceTokenString, forKey: "PushDeviceTokenString")
}
1
I think you should have a look at Cloud Functions for Firebase.AL.
Ok, i got it. Iinstalled the firebase tool via npm and also node .js. The next step ist to run firebase login. But my terminal says firebase: command not foundPeter Sypek
I got everything run. Thanks.Peter Sypek
Cool. I would suggest adding an answer below for your own post. Others may find it useful in the future. Cheers! :)AL.

1 Answers

1
votes

After i have setup firebase functions in my project according the firebase guide.

All you i had to do is create and deploy a server side function, that catches an event and performs the desired 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);
            });
        }
    });
});