Observe Users in Cloud Functions
Instagram Firebase
Now that we've implemented our Cloud Function to send push notifications to our devices, we're now ready to make this process a little more dynamic by using a user's uid instead of a raw fcmToken string. We'll first save a user's fcmToken whenever they sign up using our SignUpController. Next, we'll examine how to read information from our Realtime Database inside of a Cloud Function.

Comments (15)
mattphelps
5 years ago
Hi Brian! It's so great you are pumping out the videos! I've never learned so quickly! Is there a chance you will do a video on uploading videos? Cheers! - Matt
Brian Voong
5 years ago
mattphelps
5 years ago
Wow thankyou Brian! 5 star customer support :)
mattphelps
5 years ago
and I can't thank you enough for these courses!
gustavoame
5 years ago
Hello Brian, thanks for the awesomeness as always. I am having trouble viewing lesson #45, it seems like the video hasn't been embedded or something...
Brian Voong
5 years ago
gustavoame
5 years ago
I can view it now, thanks Brian!
Brian Voong
5 years ago
PatrickVB
5 years ago
Brian, I don't know anything about Atom and/or how to fix this Error when trying to upload the Push Notification file. (time 10:00) ✔ functions: all necessary APIs are enabled i functions: preparing functions directory for uploading... Error: Error occurred while parsing your function triggers. /private/tmp/fbfn_1265abEUY4ZZbKGz/index.js:62 }); ^
Brian Voong
5 years ago
PatrickVB
5 years ago
Thank You! After checking the code, I had commented out too far. I had to then re-save and then it Deployed successfully.
Brian Voong
5 years ago
PatrickVB
5 years ago
Outstanding Tutorial once again! Thank you for making these very complicated/complex functions understandable!
josiahsavino
5 years ago
at 2:56 you call guard let fcmToken = Messaging..... however we were not able to set up the Messaging line in app delegate because if you saw in two videos ago someone commented that "func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Registered with FCM with token:", fcmToken) " was not available anymore. What can we do? I am so far along but now stuck. Also i was not able to get the FCM because that func would not run. Can you help me overcome? lol
Brian Voong
5 years ago
josiahsavino
5 years ago
Thank you for your quick response. To help customers. Can you let them know which video and when? I really appreciate what you are doing I am just very new and overwhelmed.
Brian Voong
5 years ago
grzesiek
5 years ago
Hi Brian Great courses! But I have a problem (lesson 45). The problem began already also in lesson 44. Because I don’t see in my physical iPhone to notifications. Inside terminal by line “ firebase deploy --only functions:sendPushNotification “ send deploy complete. In console firebase in section "Functions/Logs" I see my username and fcmToken. While I refresh link I gets two error: 1.Error : " FIREBASE WARNING: Exception was thrown by user callback. ReferenceError: payload is not defined at admin.database.ref.once.snapshot (/user_code/index.js:29:51) at c (/user_code/node_modules/firebase-admin/lib/database/database.js:207:58) at /user_code/node_modules/firebase-admin/lib/database/database.js:185:831 at tc (/user_code/node_modules/firebase-admin/lib/database/database.js:77:165) at le (/user_code/node_modules/firebase-admin/lib/database/database.js:112:215) at me (/user_code/node_modules/firebase-admin/lib/database/database.js:111:632) at dh.h.Eb (/user_code/node_modules/firebase-admin/lib/database/database.js:241:287) at kh.h.ud (/user_code/node_modules/firebase-admin/lib/database/database.js:228:251) at hg.ud (/user_code/node_modules/firebase-admin/lib/database/database.js:175:364) at Pf.Xf (/user_code/node_modules/firebase-admin/lib/database/database.js:173:281) " 2.Error - “ Uncaught exception ” I will be grateful for your help
ahmadiah
5 years ago
Hi Brian, Happy New Year first! second I am wondering if FCM token will be produced based on multiple devices or based on the email address. Because if it dose depends on the device, we will need to save multiple fcmTokes in Firebase database and call the key (fcmToken) to something else so we do not overwrite. Thanks
stonypig1
5 years ago
at this 45th tutorial, cfmtoken was hard coded, then it is removed and hard coded with useruid in cloud function? is it a step mr.brian forget or missed? shouldn't be automatically figure out the user's uid in code in cloud function? or all the message will only be sent to that tea pot user (NUPR2....), anyone ? please help?
stonypig1
5 years ago
I know Mr.brian is busy working on his Podcast tutorial, if anyone else has knows please help , thanks
Brian Voong
5 years ago
stonypig1
5 years ago
i am so sorry, you are correct, after watched it 2 times, i realized user uid is replaced by the wildcard { } which later data will be retrieved by event.params. thanks so much for creating this tutorial, or i never will get to know cloud function, it was a so confusing topic for me. best 50$ ever spent, i started to think you should really charge us more on this course.
Justin Seymour
5 years ago
Hi Brian, Just checking to see if the cloud functions will work properly on the firebase free account? Getting the following log output when executing the function: 2018-03-09T05:32:38.268918372Z D sendPushNotifications: Function execution started 2018-03-09T05:32:38.268965512Z D sendPushNotifications: Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account toremove these restrictions 2018-03-09T05:32:38.380575888Z D sendPushNotifications: Function execution took 112 ms, finished with status code: 200 BTW, Thank you for all the videos, this course has been great!
Brian Voong
5 years ago
Kenny Ho
5 years ago
Hi guys, can someone in the chat share their index.js source code? My first time coding and there is so much I don't know. IDK if they updated the code but some of this isn't working for me and I'm constantly getting errors like "Command terminated with non-zero exit code1". I think they tweaked it so Brian's index.js file doesn't work. Anyone updated file would be very much appreciated! Thank you for your understanding! :)
Jeffrey Chang
5 years ago
might be easier if you show us your index.js file
h01m3s
5 years ago
Here's my code for latest Firebase Cloud Function // The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. const functions = require('firebase-functions'); // The Firebase Admin SDK to access the Firebase Realtime Database. const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.helloWorld = functions.https.onRequest((request, response) => { response.send("Hello from Firebase"); }); exports.sendPushNotifications = functions.https.onRequest((req, res) => { res.send("Attempting to send push notification...") console.log("LOGGER --- Trying to send push message...") // admin.message().sendToDevice() var uid = 'U6KL859nQMWUlSZa8F31BwcOjwY2' return admin.database().ref('/users/' + uid).once('value', snapshot => { var user = snapshot.val(); console.log("User username: " + user.username + " fcmToken: " + user.fcmToken); // See documentation on defining a message payload. var message = { notification: { title: "Push Notification Title", body: "Message Body..." }, data: { score: '850', time: '2:45' }, token: user.fcmToken }; // Send a message to the device corresponding to the provided // registration token. admin.messaging().send(message) .then((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); }) .catch((error) => { console.log('Error sending message:', error); }); }); });
rebeloper
5 years ago
My working file so far. Note: It takes a few minutes for the notification to be sent. // The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. const functions = require('firebase-functions'); // The Firebase Admin SDK to access the Firebase Realtime Database. const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); // // Create and Deploy Your First Cloud Functions // // https://firebase.google.com/docs/functions/write-firebase-functions // exports.helloWorld = functions.https.onRequest((request, response) => { response.send('Hello from Rebeloper!'); }); exports.sendPushNotifications = functions.https.onRequest((request, response) => { response.send('Attempting to send push notification...'); console.log('LOGGER --- Trying to send message...'); var uid = 'UXp0GIZlsndwXMsPm2zVD0p45zl2'; return admin.database().ref('/users/' + uid).once('value', snapshot => { var user = snapshot.val(); console.log('Username: ' + user.username + ' ; fcmToken: ' + user.fcmToken); //See documentation on defining a message payload. var message = { notification: { title: 'TITLE', body: 'BODY' }, data: { score: '850', time: '2:45' }, token: user.fcmToken }; // Send a message to the device corresponding to the provided // registration token. admin.messaging().send(message) .then((response) => { // Response is a message ID string. console.log('Successfully sent message:', response); return response; }) .catch((error) => { console.log('Error sending message:', error); throw new Error('Error sending message:', error); }); }); // This registration token comes from the client FCM SDKs. // var registrationToken = 'fTCyM8WkS4g:APA91bHRuILsb13NZj-kmDZ8JW4dnsAeNTf0nUvPlZwB733rC6EldSd3_zcFZgL9G8c84ZZeaMyhQCq23uVH3HooXgJyu26hxv45Lx65S2ia6ApS1MDeyQTAnBk0OrVb0f1qpYhB5D7X'; // //See documentation on defining a message payload. // var message = { // notification: { // title: 'TITLE', // body: 'BODY' // }, // data: { // score: '850', // time: '2:45' // }, // token: registrationToken // }; // // // Send a message to the device corresponding to the provided // // registration token. // admin.messaging().send(message) // .then((response) => { // // Response is a message ID string. // console.log('Successfully sent message:', response); // return response; // }) // .catch((error) => { // console.log('Error sending message:', error); // throw new Error('Error sending message:', error); // }); });
Clint Larenz Nurse
4 years ago
As of right now, this one works ( June 6th 2019)
tetraprism95
5 years ago
Hey Brian, everything works fine, but I'm not getting the same reception of username and token information in firebase. It deployed successfully but confused if it did work and that it's just not showing or idk. 2018-04-23T00:06:46.454945167Z D sendPushNotifications: Function execution started 2018-04-23T00:06:46.454996084Z D sendPushNotifications: Billing account not configured. External network is not accessible and quotas are severely limited. Config ure billing account to remove these restrictions 2018-04-23T00:06:46.526Z I sendPushNotifications: LOGGER --- Trying to send push notications.... 2018-04-23T00:06:46.526935715Z D sendPushNotifications: Function execution took 73 ms, finished with status code: 304 2018-04-23T00:06:46.723Z I sendPushNotifications: Successfully sent message: projects/instagramfirebase-a5ad0/messages/1524442006649915 Nuris-MBP:functions nurichun$
tetraprism95
5 years ago
Nevermind, I managed to fix everything. Will I not get the userToken and the username of the user if I run on simulator? After I ran on my device, I happened to get the info. I just wanted to know if there is any difference?
Brian Voong
5 years ago
tetraprism95
5 years ago
Hey Brian, I am not able to get the push notification on my device, but in the console/log everything checked out successfully? Any reason why that is?
Brian Voong
5 years ago
samisays11
5 years ago
You have cast apnsToken to your device token. This code should solve your problem. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Messaging.messaging().apnsToken = deviceToken print("register for FCM:", deviceToken) }
allanaraujo
5 years ago
tetraprism95 Did you ever find a solution for this? Im experiencing the same thing. samisays11, I had that in my code from the start it doesnt fix this issue.
PatrickVB
5 years ago
Good Day. I have been working through the NEW code that people have been commenting below. I am currently stuck with the JSON file uploading with no errors, I get an observerFollowing "Successfully sent message: { results: [ {error: [object] } ], canonicalRegistrationTokenCount: 0, failureCount: 1, successCount: 0, multicast: 895937471309900990000 } Any thoughts? -Patrick
Cinquain
4 years ago
More fire!
HELP & SUPPORT