I would like to add push notifications to my react native App but I would need some clarifications as there are plenty of different informations and implementations all over the web on that subject.
Currently my App is communicating with a node.js backend. So I have used the Firebase Web SDK in order to send push notifications to app clients.
Now it's time to register the app clients to Firebase Cloud Messaging in order to get tokens and save them with user related data. Then to be able to send targeted notifications to specific users (node.js backend role).
I've read to use the react native firebase library and more especially the messaging module to accomplish that.
Following that Device registration token tutorial, it's pretty clear. But where is the best place to request a token ? I assume that it should be when the user logs in to the App but we are not sure to get the token on time...
With that code we retrieve an existing token:
firebase.messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
// user has a device token
} else {
// user doesn't have a device token yet
}
});
Tell me if I'm right:
I understand that if the app instance has already a token, I'll get it and it's time to associated it with user related data in database. But if it doesn't, I need to listen for a new token using that :
componentDidMount() {
this.onTokenRefreshListener =
firebase.messaging().onTokenRefresh(fcmToken => {
// Process your token as required
});
}
componentWillUnmount() {
this.onTokenRefreshListener();
}
But where should I start listening for it ? On the login component ? If the user log in before getting the token and navigate to another component, so the login component will be unmounted. It will be still listening ? And then I need to update the user data with the token ?
Or simply when the user log in, I need to wait till getting the token before navigate to another component ?
Related
I have just started learning react-native and thinking of integrating firebase to it. Now consider my question scenario:
There are two users A & Bwho have the react app running in their device( none of them are admin). Now I have studied that when we connect our react native app to firebase, every instance of the app running on a device gets a unique token and that token is stored in firebase itself.
Now suppose user A wants to send a " notification or message" to user B. Now see the below code I saw on firebase official website:
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
var message = {
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);
})
.catch((error) => {
console.log('Error sending message:', error);
});
This method seems quite straightforward, but is there really any method using which user A can know the unique token of user B like this:
const token= firebase.getToken('B');
And then use this token in the above code to send notification to user B. Is it poosible to do it using firebase?
Thank You.
The code you found uses the Firebase Admin SDK to send messages. This SDK grants its users full administrative access to the Firebase project, so can only be used in trusted environments, such as your development machine, a server you control, or Cloud Functions. It cannot be used in the app you send to your users.
You will need a trusted environment to send the messages to the users. For more on this, see:
The Firebase documentation on FCM architecture, which has this handy diagram
How to send one to one message using Firebase Messaging
How to send Device to device notification by using FCM without using XMPP or any other script.?
I'm building an Android App that searches for nearby locations. I use Firebase login system (Login with email and password, and login with Google, Facebook, etc), therefore I would also like to build an API with Firebase. (also because I need the app to be more complicated) I have built a serverless API with Firebase Cloud Functions and I can make GET/PUT requests with Postman. However, I would like to secure these endpoints, similar to how JWT secure a RESTAPI, so that only users who logged in the App can make requests. How do I achieve this? I have looked at "authorized-https-endpoint" but it seems like it only allow Google-Sign-In.
Or is there a way that I can still use Node and Mongodb RestAPI, and secure it using the accounts logged into Firebase?
Here is a piece of the backend code
app.get('/api/read/:item_id', (req, res) => {
(async () => {
try {
const document = db.collection('items').doc(req.params.item_id);
let item = await document.get();
let response = item.data();
return res.status(200).send(response);
} catch (error) {
console.log(error);
return res.status(500).send(error);
}
})();
});
exports.app = functions.https.onRequest(app);
Thank you guys so much in advance.
Use Firebase Callable Functions. They fulfill your requirement.
Refer: https://firebase.google.com/docs/functions/callable
In the case where there are issues with the function calls, please refer to this: firebase.google.com/docs/functions/callable-reference.
As mentioned here this is to be used only if the SDKs don't work for you
The authorized-https-endpoint example supports all forms of auth on the client, as long as it's going through the Firebase Auth SDK. In all cases, the client can send an auth token to the function, and the function code can use the Firebase Admin SDK to verify the token. It doesn't matter how the user authenticated - any Firebase user account will work.
You can also use a callable function, which will automatically perform the validation for you in the exact same way. Your code must then check to see if a user was authenticated using the calling context before continuing.
How to integrate Push Notification to an already existing android app?
My android app is already available on playstore and now I wants to integrate Push Notification in next release. I have implemented it using FCM and AWS SNS.
Problem is : onNewToken method of FirebaseMessagingService will get called only when we installed the app freshly. But when we update it onNewToken method never gets call. So we cannot register the token on AWS portal while updating the app. Experts please advise how to implement this in existing app?
// Use this in your splashscreen or dashboard view.
FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener { task ->
if (!task.isSuccessful)
return#addOnCompleteListener
if(prefs.pushNotificationToken == "") {
//log the token
prefs.pushNotificationToken = task.result?.token?.trim() ?: ""
//send user push notification token to the server(use Patch instead of Post)
}
}
Doing this, both old and new user will have "pushNotificationToken" in prefs to be empty. Thus, we can fetch the token any time from firebase and send it to the backend.Or, also first we can check for token in our prefs and then only ask to firebase for token.
Problem is : onNewToken method of FirebaseMessagingService will get
called only when we installed the app freshly. But when we update it
onNewToken method never gets call. So we cannot register the token on
AWS portal while updating the app. Experts please advise how to
implement this in existing app?
You can call
FirebaseInstanceId.getInstance().getToken(senderId,"FCM");
At anytime to get an instance id to push to your server, this is a blocking call so make sure to do it on a background thread
I am thinking about keeping all registration ids(push token) in DB and sending notifications to user from iPhone. I tried something like this but did not get any notification.
func sendPNMessage() {
FIRMessaging.messaging().sendMessage(
["body": "hey"],
to: TOKEN_ID,
withMessageID: "1",
timeToLive: 108)
}
What I am doing wrong or maybe it is impossible at all?
Currently it's not possible to send messages from the application itself.
You can send messages from the Firebase Web Console, or from a custom server using the server-side APIs.
What you might want to do is to contact a server (like via http call) and that server will send the message to the user.
This way ensure that the API-KEY of the server is protected.
PS: the sendMessage(..) api is called upstream feature, and can be used to send messages from your app to your server, if you server has an XMPP connection with the FCM server.
Yes you can send push notification through Firebase.Please make sure do NOT include the server-key into your client. There are ways "for not so great people" to find it and do stuff... The Proper way to achieve that is for your client to instruct your app-server to send the notification.
You have to send a HTTP-Post to the Google-API-Endpoint.
You need the following headers:
Content-Type: application/json
Authorization: key={your_server_key}
You can obtain your server key within in the Firebase-Project.
HTTP-Post-Content: Sample
{
"notification": {
"title": "Notification Title",
"text": "The Text of the notification."
},
"project_id": "<your firebase-project-id",
"to":"the specific client-device-id"
}
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the Google Cloud Functions documentation:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
Diego's answer is very accurate but there's also cloud functions from firebase it's very convenient to send notifications in every change in the db. For example let's say you're building chat application and sending notification in every new follower change.
This function sample is very good example.
For more information about cloud functions you can check official docs.
I have an app that has a "send feedback to developer" section. I also have a User collection in my firestore database. When a user logs into the app, I have that Users data update their FCM token with the following code in my SceneDelegate.swift:
import Firebase
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil {
DispatchQueue.main.async {
let docRef = Firestore.firestore().collection("User").document((user?.email)!)
docRef.getDocument { (snapshot, error) in
guard let snapshot = snapshot else {return}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
docRef.updateData(["FCMtoken":token])
print("FCM registration token: \(token)")
}
}
}
}
}
})
guard let _ = (scene as? UIWindowScene) else { return }
}
then in my feedback view controller i have this code to send my specific device (but you can look up/fetch which specific device you want in your database where the FCMtoken is stored where i have INSERT-DEVICE-TOKEN-HERE). The url to send to is "https://fcm.googleapis.com/fcm/send" and you can find YOUR-APP-FCM-KEY by going to your project settings in firebase, going to cloud messaging tab and its the server key.
func sendMePushNotification() {
let token = "INSERT-DEVICE-TOKEN-HERE"
if let url = URL(string: "https://fcm.googleapis.com/fcm/send") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = ["Content-Type":"application/json", "Authorization":"key=YOUR-APP-FCM-KEY"]
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"title\":\"Feedback Sent!\",\"body\":\"\(self.feedbackBox.text!)\",\"sound\":\"default\",\"badge\":\"1\"},\"data\": {\"customDataKey\": \"customDataValue\"}}".data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, urlresponse, error) in
if error != nil {
print("error")
} else {
print("Successfully sent!.....")
}
}.resume()
}
}
Use onesignal,you can send device to notifications or device to segments ,it can work with firebase in this way
Use onesignal functions to create a specific id,save it in a firebase database ,then when the id can be put in another function that is used to send a notification
Notes: 1-i am using it in my apps with firebase works perfectly
2-i can submit that code,just someone comments so i can find this answer
I am thinking about keeping all registration ids(push token) in DB and sending notifications to user from iPhone. I tried something like this but did not get any notification.
func sendPNMessage() {
FIRMessaging.messaging().sendMessage(
["body": "hey"],
to: TOKEN_ID,
withMessageID: "1",
timeToLive: 108)
}
What I am doing wrong or maybe it is impossible at all?
Currently it's not possible to send messages from the application itself.
You can send messages from the Firebase Web Console, or from a custom server using the server-side APIs.
What you might want to do is to contact a server (like via http call) and that server will send the message to the user.
This way ensure that the API-KEY of the server is protected.
PS: the sendMessage(..) api is called upstream feature, and can be used to send messages from your app to your server, if you server has an XMPP connection with the FCM server.
Yes you can send push notification through Firebase.Please make sure do NOT include the server-key into your client. There are ways "for not so great people" to find it and do stuff... The Proper way to achieve that is for your client to instruct your app-server to send the notification.
You have to send a HTTP-Post to the Google-API-Endpoint.
You need the following headers:
Content-Type: application/json
Authorization: key={your_server_key}
You can obtain your server key within in the Firebase-Project.
HTTP-Post-Content: Sample
{
"notification": {
"title": "Notification Title",
"text": "The Text of the notification."
},
"project_id": "<your firebase-project-id",
"to":"the specific client-device-id"
}
Google Cloud Functions make it now possible send push notifications from device-to-device without an app server.
From the Google Cloud Functions documentation:
Developers can use Cloud Functions to keep users engaged and up to
date with relevant information about an app. Consider, for example, an
app that allows users to follow one another's activities in the app.
In such an app, a function triggered by Realtime Database writes to
store new followers could create Firebase Cloud Messaging (FCM)
notifications to let the appropriate users know that they have gained
new followers.
Example:
The function triggers on writes to the Realtime Database path where followers are stored.
The function composes a message to send via FCM.
FCM sends the notification message to the user's device.
Here is a demo project for sending device-to-device push notifications with Firebase and Google Cloud Functions.
Diego's answer is very accurate but there's also cloud functions from firebase it's very convenient to send notifications in every change in the db. For example let's say you're building chat application and sending notification in every new follower change.
This function sample is very good example.
For more information about cloud functions you can check official docs.
I have an app that has a "send feedback to developer" section. I also have a User collection in my firestore database. When a user logs into the app, I have that Users data update their FCM token with the following code in my SceneDelegate.swift:
import Firebase
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
authListener = Auth.auth().addStateDidChangeListener({ (auth, user) in
Auth.auth().removeStateDidChangeListener(self.authListener!)
if user != nil {
DispatchQueue.main.async {
let docRef = Firestore.firestore().collection("User").document((user?.email)!)
docRef.getDocument { (snapshot, error) in
guard let snapshot = snapshot else {return}
Messaging.messaging().token { token, error in
if let error = error {
print("Error fetching FCM registration token: \(error)")
} else if let token = token {
docRef.updateData(["FCMtoken":token])
print("FCM registration token: \(token)")
}
}
}
}
}
})
guard let _ = (scene as? UIWindowScene) else { return }
}
then in my feedback view controller i have this code to send my specific device (but you can look up/fetch which specific device you want in your database where the FCMtoken is stored where i have INSERT-DEVICE-TOKEN-HERE). The url to send to is "https://fcm.googleapis.com/fcm/send" and you can find YOUR-APP-FCM-KEY by going to your project settings in firebase, going to cloud messaging tab and its the server key.
func sendMePushNotification() {
let token = "INSERT-DEVICE-TOKEN-HERE"
if let url = URL(string: "https://fcm.googleapis.com/fcm/send") {
var request = URLRequest(url: url)
request.allHTTPHeaderFields = ["Content-Type":"application/json", "Authorization":"key=YOUR-APP-FCM-KEY"]
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"title\":\"Feedback Sent!\",\"body\":\"\(self.feedbackBox.text!)\",\"sound\":\"default\",\"badge\":\"1\"},\"data\": {\"customDataKey\": \"customDataValue\"}}".data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, urlresponse, error) in
if error != nil {
print("error")
} else {
print("Successfully sent!.....")
}
}.resume()
}
}
Use onesignal,you can send device to notifications or device to segments ,it can work with firebase in this way
Use onesignal functions to create a specific id,save it in a firebase database ,then when the id can be put in another function that is used to send a notification
Notes: 1-i am using it in my apps with firebase works perfectly
2-i can submit that code,just someone comments so i can find this answer