Using Google Firebase notification in React Native I am not able to access data payload onNotificationOpened.
Below is the example.
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
const { title, body } = notificationOpen.notification;
console.log(JSON.stringify(notificationOpen.data)) // {}
});
notificationOpen.notification.data is undefined.
I am triggering the API in the following format.
{
"to": <dev_token>,
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
},
"data" : {
"Nick" : "Mario",
"Room" : "PortugalVSDenmark"
}
}
using react-native-firebase : "5.5.6"
Thanks in advance.
Related
I'm creating a public chat app in Flutter, and I can't receive background notifications on iOS, when I trigger the method admin.messaging().send(payload) from my Cloud Function.
Here's my payload in the Cloud Function :
var payload = {
notification: {
title: `My Title`,
body: `My message`,
},
android: { priority: "high" },
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "10",
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
topic: `mytopic`,
};
I tried a bunch of different payloads :
I tried notification + data
I tried only data (no notification) (in that case, I have to locally display the notification, but it is not working because the function FirebaseMessaging.onBackgroundMessage is never called)
I tried to change "apns-priority" to 5
I tried using a token instead of a topic
I set up carefully all I need to configure, thanks to the official documentation :
https://firebase.flutter.dev/docs/messaging/usage/
I also checked Github issues, like these ones :
1041, 6112, 5988, 1644, 4300, 4097
What is working :
Background and foreground notifications on Android and iOS, when sent from Firebase Console (in 'Cloud Messaging' section)
Background and foreground notifications on Android only, when sent from Cloud Function
Foreground notifications on iOS, when sent from Cloud Function
What is NOT working :
Background notifications on iOS when sent from Cloud Function
When app is terminated, it does not work as well.
I finally resolved this issue ! 🎉
I simply removed the line "apns-push-type": "background" in my payload.
Now it is working.
It appears that the line "apns-topic" was useless as well.
Here is my final payload :
var payload = {
notification: {
title: `# ${context.params.passion}`,
body: `${newMsg["senderPseudo"]} ${
type == "image" ? "a envoyé une image." : `: ${newMsg["message"]}`
}`,
},
// Set Android priority to "high"
android: {
priority: "high",
},
// Add APNS (Apple) config
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
//"apns-push-type": "background", // This line prevents background notifications to be displayed
"apns-priority": "10",
},
},
token: "dnqTQVso60GfnnuOjHv8_e:APA91bElr-K3xkQMdYHX8VMrMZNCYCjO4zJlGseRh25AS_GT7cg9zlOGdQl4KXvr88ypeWjZjrPzrLRHitsQ-JKQK057ZQb_36c_lfsNjHXbYMYI2iS3jV_HGWf7Ene-ZlPvOb0aRr8u"
};
I have an Ionic 4 app which I have integrated with Firebase for authentication etc. I want to implement Firebase's cloud messaging so I can push messages to my app on both Android and iOS. I have done this pretty easily on iOS and I have sent a message via Postman which shows on my iPhone and I see the JSON of the message I have sent. When I try it on Android it doesn't work. Both devices receive the message but handle it very diferently.
I have read in a lot of places that you need to set the click_action to FCM_PLUGIN_ACTIVITY but when I do that the app doesn't even open on Android. When I take it out the app loads when you click the message but it doesn't show the body of the message like on iOS in my alert.
import { FCM } from '#ionic-native/fcm/ngx';
...
constructor(public platform: Platform, public fcm: FCM)
...
this.platform.ready().then(() => {
this.fcm.onNotification().subscribe(data => {
alert(JSON.stringify(data));
});
this.fcm.onTokenRefresh().subscribe(token => {
// Register your new token in your back-end if you want
// backend.registerToken(token);
});
}).catch((error) => {
this.showFailureMessage(error.message);
});
This is what I am posting off to... https://fcm.googleapis.com/fcm/send
{
"notification":{
"title":"My Title",
"body":"My Body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY"
"icon":"fcm_push_icon",
},
"data":{
"type":"Something",
},
"to":"/topics/all",
"priority":"high",
"restricted_package_name":""
}
Any help would be very much appreciated.
You seem to be missing the data.wasTapped part in your subscribe. Here, try this:
this.fcm.onNotification().subscribe(data => {
if (data.wasTapped) {
alert('Received in background');
alert(JSON.stringify(data));
} else {
alert('Received in foreground');
alert(JSON.stringify(data));
}
});
I'm sending push notifications from server to clients via google FCM.
In the react-native app I've registered these listeners:
this.notificationOpenedListener = firebase.notifications().onNotificationOpened(async (notificationOpen) => {
})
this.notificationListener = firebase.notifications().onNotification(async (notification) => {
});
the notification data contains information if there should be a sound / vibration or not when the notification is received.
However, I can't find any documentation about completely disabling sound/vibration on demand.
How can I achieve this?
UPDATE
I've tried setting sound to an empty string on server side, but there's still sound/vibration on notification.
var message = {
data: {
userId: fromUserId,
},
notification: {
title: `My notifcation`,
body: `Body`,
sound: "",
},
}
return sendToTopic(topicId, message)
When setting your notification target, remove sound parameter.
const notify = {
...message.notification,
show_in_foreground: true,
notify_type: message.NotificationType,
obj_id: message.ObjectId,
sound: '' // remove this
};
firebase.messaging().createLocalNotification(notify);
I'm not sure how you are setting up your Push notifications but you can tag extra data into the JSON like this:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
This means you could add a boolean to it to manually play a tone on arrival or not play a tone when the subscription fires, like this:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark",
"playTone" : "true"
}
}
}
Then it's the case of having a check in your callback to check the response:
this.notificationListener = firebase.notifications().onNotification(async (notification) => {
if(notification.data.playtone) {
// Play Tone
} else {
// Don't
}
});
In general though push notifications are handled by the OS and not the application, you can hook into it like you have and perform actions on the arrival of a push notification but normally they all arrive in the same "Drop everything and deal with me" style.
Both Android and Apple do support priority but it might not be what you're after:
https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message
I'm trying to create nodejs app with sails.js and firebase. Cannot understand how to access express part of SailsJs.
Firebase app initialized by
exports.app = functions.https.onRequest(app);
app - express app.
Sails app initialized by
sails.lift(rc('sails'));
Tried to access to sails.hooks.http.app but it is undefined. Any ideas?
Thanks
hi you can use this piece of code to to execute fire base messaging services and in same manner other services too
var request = require('request');
function sendMessageToUser(deviceId, message) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key=AI...8o'
},
body: JSON.stringify(
{ "data": {
"message": message
},
"to" : deviceId
}
)
}, function(error, response, body) {
if (error) {
console.error(error, response, body);
}
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body);
}
else {
console.log('Done!')
}
});
sendMessageToUser(
"d7x...KJQ",
{ message: 'Hello puf'}
);
as sails provide a method mentioned below ,but i was not able find exact example to implement Firebase with it so i used core node to explain it , I will be updating this answer after i finished with this method and sails + Firebase
res.created()
hope this helps you in your work
https://github.com/kristinyim/ClassroomChat
I want to add an upvoting feature to the messages on this chatroom similar to what you have on GroupMe, but I'm new to React and built this off of a tutorial so don't know where to even begin. I'm good with webdev but am just getting started with the basics of React.js and Firebase. Thanks!
NB: There are many ways to achieve this, so the following is just a suggestion.
First you must think of how you want to store your data in the database. If you have users, messages and message-likes, you could structure it like this:
"root": {
"users": {
"$userId": {
...
"messages": {
"$messageId1": true,
"$messageId2": true,
...
}
}
},
"messages": {
"$messageId": {
"author": $userId,
"timestamp": ServerValue.TIMESTAMP
}
},
"likesToMessages": {
"$messageId": {
"$likeId": {
liker: $userId,
"message": $messageId,
"timestamp": ServerValue.TIMESTAMP
}
}
}
}
Whenever a user clicks "like" on a message, you want to write to
var messageId = ?; // The id of the message that was liked
var like = {
liker: currentUserId, // id of logged in user
message: messageId,
timestamp: firebase.database.ServerValue.TIMESTAMP
};
firebase.database.ref().child('likesToMessages').child(messageId).push(like);
Then you get a new like in the database, matching the proposed structure.
Then, when you want to read and show the count of likes for a message, you can do like this:
const Message = React.createClass({
propTypes: {
message: React.PropTypes.object,
messageId: React.PropTypes.string // you need to add this prop
}
componentWillMount() {
firebase.database.ref().child('likesToMessages').child(this.props.messageId).on('value', this.onLikesUpdated)
}
onLikesUpdated(dataSnapshot) {
var likes = snap.val();
this.setState({
likes
});
}
render() {
const {name, message} = this.props.message;
const emojifiedString = emoji.emojify(message);
return (
<p>
{name}: {emojifiedString} [{this.state.likes.length}♥]
</p>
);
}
});
Also, in your database security rules, you'd want to index by timestamp for message and like so you can quickly query the newest messages.
Also, feel free to check out a similar app I made, code in GitHub and demo on wooperate.firebaseapp.com.