I have implemented firebase cloud messaging for my react-native app and now I am able to send and receive Notifications.
But now I want to get the Notifications Data like messages, right after clicking on it.
Why I need this ?
Because I have A simple chat app, and suppose I have three rooms, room1, room2, room3.
Now my App is closed and I receive Notification from room1, then I click on that, At this time I expected it open my app and navigate to the room1 chatbox, and the other rooms notifications too.
Any help?
note: I am using react-native-firebase v6
Cloud Messaging is only used to send messages from a server on the phone.
Before, on firebase 5, we had a package called "notifications" which allowed us to manage the interception of data when you clicked on it.
Since Firebase 6, this package doesn't exist anymore (well, in a way it will become paying and this service is called Notifee but it is still in test).
You have to use external packages such as react-native-push-notifications which allows you to intercept push notifications data.
async componentDidMount() {
this.createNotificationListeners();
}
async createNotificationListeners() {
this.notificationListener = firebase.notifications().onNotification((notification) => {
console.log(':::::::::::::::::::::::::::: APPLICATION OPEN MODE :::::::::::::::::::::::::::');
console.log(notification, 'APPLICATION OPEN');
// Manage Notifiacation
// firebase.notifications().removeDeliveredNotification(notification._notificationId);
});
const channel = new firebase.notifications.Android.Channel('fcm_FirebaseNotifiction_default_channel', 'JobApp', firebase.notifications.Android.Importance.High)
.setDescription('DEMO NOTIFICATION DESCRIPTION');
firebase.notifications().android.createChannel(channel);
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
console.log(':::::::::::::::::::::::::::: APPLICATION WORKING IN BACKGROUND MODE :::::::::::::::::::::::::::');
console.log(notificationOpen.notification.data);
const { notificationType } = notificationOpen.notification.data;
console.log(notificationType)
firebase.notifications().removeDeliveredNotification(notificationOpen.notification._notificationId);
});
const notificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
console.log(':::::::::::::::::::::::::::: APPLICATION CLOSED :::::::::::::::::::::::::::');
console.log(notificationOpen);
}
this.messageListener = firebase.messaging().onMessage((message) => {
console.log(JSON.stringify(message));
});
}
Related
I am using ionic with vue js mobile app. I want to trigger event from client side when location on mobile user is changed.
methods: {
getLocation: function () {
const geolocation = new GeolocationService.Geolocation();
let watch = geolocation.watchPosition();
watch.subscribe((data) => {
console.log('data',data)
//Trigger pusher event here
});
},
},
And then I want to listen that event on my web app with help of jquery.
But I don't know how I can trigger pusher event from client side
I am using this pusher package
https://www.npmjs.com/package/vue-pusher
The Pusher documentation about triggering client events has every information for your case.
Starting with:
Not all traffic needs to go via your conventional web server when using Channels. Some actions may not need validation or persistence and can go directly via the socket to all the other clients connected to the channel.
Some other important things to highlight:
Client events must be enabled for the application inside Pusher dashboard.
The user must be subscribed to the channel that the event is being triggered on.
Client events can only be triggered on private and presence channels because they require authentication. So understanding Pusher authentication is a must.
Publish no more than 10 messages per second per client (connection). So user location changing every second shouldn't be a problem.
Using a wrapper like vue-pusher is totally optional, you can always instantiate a new Pusher and use the client directly. But if you really like the wrapper, your code could be something like that:
export default {
data() {
return {
channel: null
};
},
created() {
this.channel = this.$pusher.subscribe('private-positions');
},
methods: {
getLocation() {
const geolocation = new GeolocationService.Geolocation();
const watchPosition = geolocation.watchPosition();
watchPosition.subscribe((data) => {
this.channel.trigger("client-positionChanged", {
data
});
});
}
}
}
Of course the Pusher authentication part should be considered too.
I'm using firebase-functions/lib/logger to log client-side firebase/firestore activity like
const { log, error } = require("firebase-functions/lib/logger");
export const addData = async (userId, dataId) => {
try {
const collectionRef = firestore
.collection("docs")
await collectionRef.add({
dataId,
});
log(`Data added`, { userId, dataId });
} catch (err) {
error(`Unable to add new data`, { userId, dataId });
throw new Error(err);
}
};
When I run this on my local, the log shows up in my browser console. Will this happen on non-local environments, ie for real users? Will these logs also show up automatically in Stackdriver, or are they stuck on the client side? I want to be able to view the logs either in Stackdriver or Firebase console but have them not show up in the browser for real users. How should I accomplish this?
Messages logged in Cloud Functions will not show up in the client app at all (that would probably be a security hole for your app). They will show up in the Cloud Functions console in the log tab, and in StackDriver.
Any messages logged in your app will not show up in any Google Cloud product. They are constrained to the device that generated them. If you want cloud logging, you'll need to implement some other solution. Cloud Functions does not support this - you will need to investigate other solutions or build something yourself.
I am trying to send a push notification every time a child is created with no success.
I am creating a child with 2 token names with a question mark between them and trying to send to those tokens the notification.
to get the tokens from the phones I am using
new FirebaseMessaging().getToken() .
here is the firebase functions code
`
// // 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 Firebase!");
// });
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
exports.onNewMessage = functions.database.
ref('/messages/{pushId}')
.onCreate((snapShot,context)=>{
var str = snapShot.key();
var res = str.split("?");
// Notification details.
const payload = {
notification: {
title: 'title!',
body: `body!`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
// Send notifications to all tokens.
admin.messaging().sendToDevice(res[0], payload);
admin.messaging().sendToDevice(res[1], payload);
});` .
This may have many if-thens, but I will describe here the most common sources of errors
1) Did not grant permissions for notifications for iOS/Android platform. For Android it is fine, and relatively easy to receive notifications, but for iOS you need Developer account to do that (on December 2019 it was 99$ per year)
2) I would recommend using topic subscription instead of tokenization (i.e. .getToken()) as it removes burden of following every single sent message manually
For example:
final fbmsg = FirebaseMessaging();
fbmsg.requestNotificationPermissions();
fbmsg.configure(onMessage: (msg) {
print(msg);
return;
}, onLaunch: (msg) {
print(msg);
return;
}, onResume: (msg) {
print(msg);
return;
});
fbmsg.subscribeToTopic('chats');
You can configure onLaunch, onResume, and onMessage behaviors on your own demand
For (1) and (2), a great place to start is following documentation of firebase_messaging library
3) I am not sure about this, but I think a better way to use index.js file could be using the snapshot that you receive (or at least try console.log() of whatever you get to check validity). But if it works for you, just ignore this step :) Below I attach the code from my app with working notifications
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.myFunction = functions.firestore
.document('chats/{message}')
.onCreate((snapshot, context) => {
return admin.messaging().sendToTopic('chats', {
notification: {
title: snapshot.data().username,
body: snapshot.data().text,
clickAction: 'FLUTTER_NOTIFICATION_CLICK'
},
});
});
4) I had hard time with establishing this Firebase Functions feature, also check installation steps for them as well
5) Check how you are trying to send the notification, first try to simulate it from the console, make sure that receiving part works, and then try to create an automated one
Hope it helped!
I've created an app to test push notifications in a flutter app.
I am able to send a notification from the firebase messaging console and I can receive it as well in the foreground and background.
Once I've done this, I moved to the next step which is to send it automatically using the firebase cloud messaging service and I've used javascript and I've deployed function and it gets executed without any problem.
But the problem is that I can't receive a notification like this:-
but when I open my app since I've configured the firebase messaging inside initState(); I can see the notification and data get printed as well but I can't receive it like the photo above.
What should I do?
try to have a background handler or a top-level method as firebase messaging plugin's read me file says.
About my javascript index.js file:
It sends a notification for all the tokens in the pushTokens collection when a new document added to the posts collection and it does this but the problem is that I've mentioned above.
Index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var notificationMessageData;
exports.fcmTester = functions.firestore.document('posts/{postID}').onCreate((snapshot, context) => {
const notificationMessageData = snapshot.data();
return admin.firestore().collection('pushTokens').get()
.then(snapshot => {
var tokens = [];
if (snapshot.empty) {
console.log('No Devices');
throw new Error('No Devices');
} else {
for (var token of snapshot.docs) {
tokens.push(token.data().tokenID);
}
var payload = {
"notification": {
"title": "from" + notificationMessageData.writer,
"body": "from" + notificationMessageData.name,
"sound": "default"
},
"data": {
"sendername": notificationMessageData.writer,
"message": notificationMessageData.name
}
}
return admin.messaging().sendToDevice(tokens, payload)
}
})
.catch((err) => {
console.log(err);
return null;
})
});
Put your app in background and try sending notification again bcoz flutter firebase messaging plug-in will not create notification if you are using the app while the notification has been sent although you can see its data in but to generate notification you have to do it manually if user is currently using the app.
On the other cases plug-in will create notification like if app is terminated or its in background.
I am new to React-Naive and trying to build an app that sends message through app using react-native-get-sms-android.
I am able to send and read SMS from inbox but there is no Event in the package to know if a new sms has been received.
Is there any Event or API in react native for this?
I think I will have to use polling to check if a new sms has arrived.
You can either create your own native module or use react-native-android-sms-listener to listen for the new messages similar to Whatsapp.
Manual Installation is provided in the docs
Usage
import SmsListener from 'react-native-android-sms-listener'
componentDidMount() {
this.subscription = SmsListener.addListener(message => {
console.info(message)
})
}
componentWillUnmount() {
this.subscription.remove()
}
where the contents are in the format
{
originatingAddress: string,
body: string
}
Also make sure that you need specific permissions to read SMS for android, check the permissions docs here