I'm trying to implement push notification with React Native and Firebase through this documentation.
I set up the settings I need by the tutorial.
import React, { Component } from 'react'
import { View } from 'react-native'
import { Input, Text, Button } from '../Components'
import type { RemoteMessage } from 'react-native-firebase'
import firebase from 'react-native-firebase'
import type { Notification, NotificationOpen } from 'react-native-firebase';
export default class TestComponent extends Component {
async componentDidMount() {
await this.SetUpAuth();
await this.SetUpMessaging();
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
});
const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
if (notificationOpen) {
console.log(notificationOpen)
// App was opened by a notification
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification: Notification = notificationOpen.notification;
}
}
componentWillUnmount() {
}
async SetUpAuth() {
const credential = await firebase.auth().signInAnonymouslyAndRetrieveData();
if (credential) {
console.log('default app user ->', credential.user.toJSON());
} else {
console.error('no credential');
}
}
async SetUpMessaging() {
this.notification2 = new firebase.notifications.Notification()
.setNotificationId('notificationId')
.setTitle('My notification title')
.setBody('My notification body')
.android.setChannelId('test')
.android.setClickAction('action')
.setData({
key1: 'value1',
key2: 'value2',
});
this.notification2
.android.setChannelId('channelId')
.android.setSmallIcon('ic_launcher');
console.log('assa')
onTokenRefreshListener = firebase.messaging().onTokenRefresh(fcmToken => {
console.log('token generated ->', fcmToken);
// store.dispatch(DeviceActions.SetFCMToken(fcmToken));
});
const fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
// user has a device token
console.log('has token ->', fcmToken);
console.log(firebase.auth().currentUser._user)
firebase.database().ref(`/users/${firebase.auth().currentUser._user.uid}`).set({ pushToken: fcmToken })
// store.dispatch(DeviceActions.SetFCMToken(fcmToken));
} else {
// user doesn't have a device token yet
console.error('no messaging token');
}
const messagingEnabled = await firebase.messaging().hasPermission();
if (messagingEnabled) {
// user has permissions
console.log('User has FCM permissions');
} else {
// user doesn't have permission
console.log('User does not have FCM permissions');
await this.RequestMessagePermissions();
}
messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
console.log(`Recieved message - ${JSON.stringify(message)}`);
});
notificationDisplayedListener = firebase
.notifications()
.onNotificationDisplayed(notification => {
// Process your notification as required
// ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
console.log(`Recieved notification 1`);
});
notificationListener = firebase
.notifications()
.onNotification(notification => {
console.log(notification)
firebase.notifications().displayNotification(this.notification2)
// Process your notification as required
console.log(`Recieved notification 2`);
});
}
async RequestMessagePermissions() {
console.log('request')
console.log('Requesting FCM permission');
await firebase
.messaging()
.requestPermission()
.catch(err => console.err(err));
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
</View>
)
}
When I try to use it in postman I get success:
{
"success": {
"results": [
{
"messageId": "0:1525013439417985%a0cec506a0cec506"
}
],
"canonicalRegistrationTokenCount": 0,
"failureCount": 0,
"successCount": 1,
"multicastId": 6840884736220792000
}
}
But in my debugger (by console.log) I don't see any new incoming message or something else. I sent a message to my device with the token I added to this post but nothing happened.
it works only when app is in foreground, But I want to make it work also when app in background/closed the app
As mentioned in the docs you need onNotificationOpened listener for android, when the app is in background
Android Background: onNotificationOpened triggered if the notification is tapped.
onNotificationDisplayed is for IOS app in background and triggered if content_available set to true
notificationBackgroundListener = firebase
.notifications()
.onNotificationOpened(notification => {
// Process your notification as required
console.log(`Recieved notification 2`);
});
If your notification is working fine when your app is in foreground then the problem is with your service. There are two possible reasons it's not working.
Either you are sending the payload as
{
time_to_live: 86400,
collapse_key: "xxxxxx",
delay_while_idle: false,
registration_ids: registration_ids,
notification: payload
}
instead of
{
time_to_live: 86400,
collapse_key: "xxxxxx",
delay_while_idle: false,
registration_ids: registration_ids,
data: payload
}
which is because the key in notification is recieved only when app is in foreground.
Another possible reason could be the service worker is getting killed for some reason. ex: I was using a one plus which auto kills the service when I force close the app. So you can try debugging your service in native code by adding log or attaching a debugger
also make sure to add google-service.json file in your android/app folder
Edit:
{
"registration_ids" : ["reg_id"],
"time_to_live": 86400,
"collapse_key": "test_type_b",
"delay_while_idle": false,
"notification": {},
"data": {
"subText":"sub title R",
"title":"Notification Heading R",
"message":"Short big text that will be shown when notification is expanded R",
"color":"red",
"actions": ["hello", "welcome"],
"vibrate": true,
"vibration": 1000,
"ticker": "My Notification Ticker",
"imageUrl": "https://cdn-images-1.medium.com/max/712/1*c3cQvYJrVezv_Az0CoDcbA.jpeg" ,
"bigText": "blalMy big text that will be shown when notification is expanded"
}
}
Here is my headers
Authorization: key=mykey:myKey
Content-Type: application/json
Request:
https://fcm.googleapis.com/fcm/send
which is of post and params are of raw type
you can use Headless JS to run task in background and you should write some native code to handle task , unfortunately is only available in android
https://facebook.github.io/react-native/docs/headless-js-android.html
second way(i don't test it) is to use this library
https://github.com/jamesisaac/react-native-background-task#installation
ps:firebase and other push notification service like onesignal handle push notification easily and you should not be concerned unless you want unique notification for each user
Related
I'm attempting to set up push notifications using Twilio Conversations and Firebase Cloud Messaging on a Next.js 12 app. The documentation is written with the assumption of using Firebase 8 syntax, but I'm using Firebase 9 in this scenario. I've been struggling to get push notifications to work while the page is open. I have the service worker set up (per Firebase docs) but it doesn't seem to be recognizing that a new message is being received from Twilio in order to actually show the notification.
Docs I've followed:
https://www.twilio.com/docs/conversations/javascript/push-notifications-web
https://firebase.google.com/docs/cloud-messaging/js/client
What I've tried
On my backend, I pass the Push Credential SID when I construct a new ChatGrant:
const chatGrant = new ChatGrant({
pushCredentialSid: process.env.TWILIO_PUSH_CREDENTIAL_SID,
serviceSid: CONVERSATIONS_SID
});
In the frontend, I followed the Twilio documentation to set up Firebase:
init.ts
import { getMessaging, getToken, onMessage } from "firebase/messaging";
import { initializeApp } from "firebase/app";
import { Client } from "#twilio/conversations";
// Omitted
const firebaseConfig = {};
export function getPermission(client: Client) {
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
getToken(messaging, { vapidKey:"KEY" })
.then((data) => {
console.log({ data });
client.setPushRegistrationId("fcm", data).catch((error) => {
console.error({ error });
});
onMessage(messaging, (payload) => {
console.log({ payload });
client.handlePushNotification(payload).catch((error) => {
console.error(error);
// test
});
});
})
.catch((error) => {
console.error(error);
// test
});
}
I call getPermission from this file once when the conversation app loads.
// chatClient is stored in a ref so it doesn't recalculate/refetch/reauthorize all the time
const chatClient = useRef(null);
// [Other code]
chatClient.current = new ConversationClient(data.chatAccessToken);
chatClient.current.on("connectionStateChanged", async (state) => {
switch (state) {
case "connected": {
// Only get permission once the chat client is fully set up
getPermission(chatClient.current);
// ..........
And my service worker firebase-messaging-sw.js:
importScripts('https://www.gstatic.com/firebasejs/9.14.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.14.0/firebase-messaging-compat.js');
if (!firebase.apps.length) {
firebase.initializeApp({
// CONFIG GOES HERE
});
}
const messaging = firebase.messaging();
//background notifications will be received here
messaging.onBackgroundMessage(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/android-chrome-192x192.png'
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
What's happening
In the service worker, messaging.onBackgroundMessage never appears to be invoked. I don't know where this issue is derived from - is Twilio not passing message info to Firebase? Or is Firebase not listening to when Twilio sends it the information? Has that changed from v8 to v9?
In init.ts, onMessage is never invoked. Same deal here, is Twilio not passing the right information to Firebase, or did I misconfigure something?
I'm not getting any console errors or warnings, and the network tab is not pointing out anything super helpful.
I got this to work by using the example code (from docs) and configuring my Next.js application to compile the TypeScript into JavaScript. This helped a lot: https://github.com/vercel/next.js/issues/33863#issuecomment-1140518693
I'm building a chat app with React and Firebase and I'm using functional React components. Please I would like to find out if there is a way to send a user an email if a message has not been read after one hour. I'm using triggerEmail to send emails when a property is created like this:
const formik = useFormik({
... //some other code here
onSubmit: async (values) => {
... //some other code here
await addDoc(collection(db, "mail"), {
to: values.email,
template: {
name: 'Property Uploaded',
data: {
id: values.id
}
}
})
}
})
This code runs when a property is created and an email is sent to the user as well as the admin. There's also a chat feature where users can send messages to the admin and this is wrapped in a custom react hook.
export default function useSendMessage() {
const [error, setError] = useState(null)
const { user } = useAuthContext()
const sendMessage = async (admin, agent, message) => {
setError(null)
try {
await addDoc(collection(db, "messages", admin.id, "messages"), {
admin: admin,
agent: agent,
isSender: admin.id === user.uid,
message: message.trim(),
markRead: false,
created_at: moment().format()
})
await addDoc(collection(db, "messages", agent.id, "messages"), {
admin: admin,
agent: agent,
isSender: agent.id === user.uid,
message: message.trim(),
markRead: false,
created_at: moment().format()
})
} catch (error) {
setError(error.message)
}
}
return { error, sendMessage }
}
And I'm using this hook in the chat app like this:
import useSendMessage from "../../hooks/useSendMessage";
export default function UserMessageInput({ admin, agent }) {
...//some code here
const handleSubmit = async (e) => {
e.preventDefault()
setSending(true)
setMessage("")
await sendMessage(admin, agent, message)
.then(() => {
setSending(false)
})
}
return(
...//chat app UI
)
}
Is there a way to trigger the email service if markRead is false after one hour? I would like to notify the admin or the agent that they have a new message on the site. I'm not sure setTimeout or setInterval can work because the agent or the admin might be offline at certain times.
You can schedule a Cloud Function to run in exactly one hour after the message doc has been created, as explained in this article titled "How to schedule a Cloud Function to run in the future with Cloud Tasks (to build a Firestore document TTL)".
Concretely, in the HTTP callback function that is invoked by Cloud Tasks you will first check the value of the markRead boolean field in the Firestore document and, if it is false, you'll send the email by creating a doc in the mail collection, since you use the Email extension.
Another approach would be to use a scheduled Cloud Function to run e.g. every minute, checking is the message was create more than one hour ago and is not marked as read. The above referred article explains the drawbacks of this approach.
EDIT: As of 9/12/2021, this method of requesting permissions has been depreciated for anything passed Expo SKD Version 40.
I am trying to request a user's location. I tried writing an async function to tell me if my request was processed, but it is ignored. I am prompted with a "location request" but I believe it is actually the Expo app and not my function.
Below is some of my code:
import React, { useState, useEffect, Component }from "react";
import { Permissions , Request } from 'expo-permissions'
//This is the async function I wrote to prompt the user to give permission
async function getLocationAsync(){
const { status, permissions } = await Permissions.askAsync( Permissions.LOCATION);
if (status === 'granted'){
console.log('It worked!')
}
else {
throw new Error('Location permission not granted');
}
}
//This logs the terminal and lets me know that the user's current location has been isolated (mounting). When the app no longer needs their location, it dismounts to prevent a memory leak.
const Screen = ({navigation})=> {
const [user_latitude, setUserLatitude] = useState(0)
const [user_longitude, setUserLongitude] = useState(0)
const [position_error, setPositionError] = useState(null)
useFocusEffect(
React.useCallback(()=> {
let isActive = true;
const fetchGeoPosition = () => {
navigator.geolocation.getCurrentPosition(
position => {
if (isActive){
setUserLatitude(position.coords.latitude);
setUserLongitude(position.coords.longitude);
setPositionError(null);
console.log('Location Accessed')
}
setIsLoading(false)
},
error => isActive && setPositionError(error.message),
{enableHighAccuracy: true, timeout: 0, maximumAge: 1000}
);
}
fetchGeoPosition()
return () =>{
isActive = false
console.log('Location Severed')
}
},
[],
),
)
Check this library for Permission on react-native
Here's https://www.npmjs.com/package/react-native-permissions.
For Android only there a default Package in react-native. ( PermissionAndroid)
https://reactnative.dev/docs/permissionsandroid
Update your manifest file also. Indicating that the application going to use external resource which requires user permission.
https://developer.android.com/guide/topics/manifest/uses-permission-element
And For iOS update info.plist file
https://www.iosdev.recipes/info-plist/permissions/
I am using the latest react native version 0.62 and latest version of react-native-firebase i.e. v6. I am able to get the notification and it working fine on the background but its not displaying on foreground.
Here is the screenshot:
And here is my code:
checkPermission = async () => {
const enabled = await messaging().hasPermission();
console.log('enabled ******* ',enabled)
if (enabled) {
this.getFcmToken();
} else {
this.requestPermission();
}
};
getFcmToken = async () => {
const fcmToken = await messaging().getToken();
if (fcmToken) {
console.log('Your Firebase Token is:', fcmToken);
// this.showAlert('Your Firebase Token is:', fcmToken);
} else {
console.log('Failed', 'No token received');
}
};
requestPermission = async () => {
try {
await messaging().requestPermission();
// User has authorised
} catch (error) {
// User has rejected permissions
}
};
messageListener = async () => {
console.log('inside message listener ****** ')
messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
};
showAlert = (title, message) => {
Alert.alert(
title,
message,
[{ text: 'OK', onPress: () => console.log('OK Pressed') }],
{ cancelable: false },
);
};
componentDidMount() {
this.checkPermission();
this.messageListener();
}
By default rnfirebase not supporting displaying notification popup when app is in foreground state as they mentioned here. So push notification pop up only displayed when app is in background state or closed.
So if you want to display push notification on foreground mode also then you have to use extra library which will be display fired push notification as local notification as mention in their documentation.
If the RemoteMessage payload contains a notification property when sent to the onMessage handler, the device will not show any notification to the user. Instead, you could trigger a local notification or update the in-app UI to signal a new notification.
So as a solution you can use react-native-push-notification to fire push notification when app in foreground.
To do so, just install it by command :
npm i react-native-push-notification
For android you don't need to follow any native installation steps just install library by this command and then you can fire local push notification as below :
Create a file called NotificationController.android.js :
import React, { useEffect } from 'react';
import { Alert } from 'react-native';
import messaging from '#react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';
const NotificationController = (props) => {
useEffect(() => {
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
PushNotification.localNotification({
message: remoteMessage.notification.body,
title: remoteMessage.notification.title,
bigPictureUrl: remoteMessage.notification.android.imageUrl,
smallIcon: remoteMessage.notification.android.imageUrl,
});
});
return unsubscribe;
}, []);
return null;
};
export default NotificationController;
Now, when app is in foreground state and if onMessage receive any message from firebase then PushNotification will fire local notification.
Update: For iOS
For iOS you have to install #react-native-community/push-notification-ios using this command:
npm i #react-native-community/push-notification-ios
Also follow all the native installation steps as suggested in document.
Then you can create file called NotificationController.ios.js where you can handle notification for iOS.
import { useEffect } from 'react';
import { Alert } from 'react-native';
import messaging from '#react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';
import PushNotificationIos from '#react-native-community/push-notification-ios';
const NotificationController = (props) => {
const navigation = useNavigation();
// Called when application is open by clicking on notification
// and called when application is already opend and user click on notification
PushNotification.configure({
onNotification: (notification) => {
if (notification) {
console.log(notification);
Alert.alert('Opened push notification', JSON.stringify(notification));
}
},
});
useEffect(() => {
// Usesd to display notification when app is in foreground
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
PushNotificationIos.addNotificationRequest({
id: remoteMessage.messageId,
body: remoteMessage.notification.body,
title: remoteMessage.notification.title,
userInfo: remoteMessage.data,
});
});
return unsubscribe;
}, []);
return null;
};
export default NotificationController;
Now, call <NotificationController /> in you Home screen or App initial routing file.
I agree with all the above solutions...
I just wanted to add that, if you don't have channel id the use
PushNotification.createChannel(
{
channelId: 'fcm_fallback_notification_channel', // (required)
channelName: 'My channel', // (required)
channelDescription: 'A channel to categorise your notifications', // (optional) default: undefined.
soundName: 'default', // (optional) See `soundName` parameter of `localNotification` function
importance: 4, // (optional) default: 4. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration patten if true.
},
created => console.log(`createChannel returned '${created}'`),
);
and be careful while using
const dat = {
channelId: 'fcm_fallback_notification_channel', // (required)
channelName: 'My channel',
//... You can use all the options from localNotifications
message: notification.body, // (required)
title: notification.title,
};
console.log(dat)
PushNotification.localNotification(dat);
In some case when title: undefined, or title: Object{}, same for message might be happening so console log every thing and put it inside localNotification fuction
Following #Kishan Bharda solution, I had to do something different for IOS foreground notifications (here, I have the code in index.js instead of a different file):
import { AppRegistry, Platform } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import PushNotificationIOS from "#react-native-community/push-notification-ios";
import PushNotification from "react-native-push-notification";
if (Platform.OS === 'ios') {
// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
const { foreground, userInteraction, title, message } = notification;
if (foreground && (title || message) && !userInteraction) PushNotification.localNotification(notification);
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
});
}
AppRegistry.registerComponent(appName, () => App);
I am developing an app in React Native and I want to implement logging in with Facebook.
I have an API in Node.js where I handle the logic for users to log in, etc.
I use passport.js to let users log in with either Facebook or traditional Email.
I am opening an URL in my API with SafariView which is just a regular "WebView" directly in my app.
I have tried using the following code:
class FacebookButton extends Component {
componentDidMount() {
// Add event listener to handle OAuthLogin:// URLs
Linking.addEventListener('url', this.handleOpenURL);
// Launched from an external URL
Linking.getInitialURL().then((url) => {
if (url) {
this.handleOpenURL({ url });
}
});
}
componentWillUnmount() {
Linking.removeEventListener('url', this.handleOpenURL);
}
handleOpenURL({ url }) {
// Extract stringified user string out of the URL
const [, user_string] = url.match(/user=([^#]+)/);
this.setState({
// Decode the user string and parse it into JSON
user: JSON.parse(decodeURI(user_string))
});
if (Platform.OS === 'ios') {
SafariView.dismiss();
}
}
openURL(url) {
if (Platform.OS === 'ios') {
SafariView.show({
url: url,
fromBottom: true,
});
} else {
Linking.openURL(url);
}
}
render() {
return (
<Button
onPress={() => this.openURL('https://mywebsite.com/api/auth/facebook')}
title='Continue with Facebook'
...
so I guess I will have to do the authentication on URL https://mywebsite.com/api/auth/facebook and then send the user to an url that looks something like OAuthLogin://..., but I am not entirely sure how to use it.
Can anyone help me move in the right direction?
import { LoginManager, AccessToken } from 'react-native-fbsdk'; // add this file using npm i react-native-fbsdk
Create function
const onFacebookButtonPress = async () => {
// Attempt login with permissions
const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);
if (result.isCancelled) {
throw 'User cancelled the login process';
}
// Once signed in, get the users AccesToken
const userInfo = await AccessToken.getCurrentAccessToken();
if (!userInfo) {
throw 'Something went wrong obtaining access token';
}
console.log('user info login', userInfo)
// Create a Firebase credential with the AccessToken
const facebookCredential = auth.FacebookAuthProvider.credential(userInfo.accessToken);
setGoogleToken(userInfo.accessToken)
// Sign-in the user with the credential
return auth().signInWithCredential(facebookCredential)
.then(() => {
//Once the user creation has happened successfully, we can add the currentUser into firestore
//with the appropriate details.
console.log('current User ####', auth().currentUser);
var name = auth().currentUser.displayName
var mSplit = name.split(' ');
console.log("mSplit ",mSplit);
let mUserDataFacebook = {
user_registration_email: auth().currentUser.email,
user_registration_first_name: mSplit[0],
user_registration_last_name: mSplit[1],
registration_type: 'facebook',
user_registration_role: "Transporter",
token: userInfo.accessToken,
user_image : auth().currentUser.photoURL,
};
console.log('mUserDataFacebook',mUserDataFacebook)
LoginWithGoogleFacebook(mUserDataFacebook) /// Call here your API
firestore().collection('users').doc(auth().currentUser.uid) //// here you can add facebook login details to your firebase authentication.
.set({
fname: mSplit[0],
lname: mSplit[1],
email: auth().currentUser.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
userImg: auth().currentUser.photoURL,
})
//ensure we catch any errors at this stage to advise us if something does go wrong
.catch(error => {
console.log('Something went wrong with added user to firestore: ', error);
})
})
}
Call this function on button press onFacebookButtonPress()
For android need to setup and add facebook id in
android/app/src/main/res/values/strings.xml file
add these two lines.
YOUR_FACEBOOK_ID
fbYOUR_FACEBOOK_ID //Don't remove fb in this string value
/////////////add this code in AndroidMainfest.xml file
//////////This code add in MainApplication.java file
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
/////////add code build.gradle file
implementation 'com.facebook.android:facebook-android-sdk:[5,6)'