Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Adding Firebase PUSH Notifications for Android/iOS Using React Native and Expo

Tiempo de lectura: 5 minutos

Reading time: 6 minutes

Hello, today I’m going to show you how to add PUSH notifications to receive messages in your React Native projects using React Native Firebase Notifications.

The first thing to do is to register the app in Firebase:

  1. Create a new project and add the iOS and Android APP.

In the case of iOS:

  • Fill in all the requested data, the package ID (which can be found in app.json > ios > bundleIdentifier).
  • APP name to be displayed in Firebase (in my case, I put “iOS APP name”).
  • It will generate a configuration file named GoogleService-Info.plist, which we need to add to the path indicated in our APP’s iOS folder (if you haven’t generated the folders, here’s how to do it). This process will be automatically done by EXPO.
  • Add this file to the root of our project.
  • In order to configure the rest of the settings automatically, we need to go to our app.json file and add the following:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"ios": {
"googleServicesFile": "./GoogleService-Info.plist",
}
"ios": { "googleServicesFile": "./GoogleService-Info.plist", }
"ios": {
 "googleServicesFile": "./GoogleService-Info.plist",
}

Now we need to open the project with Xcode to add the PUSH notification module.

Go to capabilities and click on + Capability

Then search for Push Notifications and Background Modes.

here’s how to do it). Expo will do this process automatically.

 

  • Add this file to the root of our project:
  • To configure the rest of the things automatically, we need to go to our app.json file and add the following:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"ios": {
"googleServicesFile": "./GoogleService-Info.plist",
}
"ios": { "googleServicesFile": "./GoogleService-Info.plist", }
"ios": {
 "googleServicesFile": "./GoogleService-Info.plist",
}

Now we need to open the project with Xcode to add the PUSH notification module.

Go to capabilities and click on + Capability

After that, search for Push Notifications and Background Modes.

Under Background Modes, check Remote notifications:

We can now close the project opened in Xcode.

Next, we need to generate the APN certificate, so follow these steps:

  • Go to the iOS developer console (remember to have a developer account).
  • Go to certificates:

Now click on keys:

Add a new key:

And add the key ID, which can be found in the Apple development console when clicking on the generated key:

And the Team ID, which is displayed in the top bar below the name (when you’re logged in). It also appears in the account section:

With this, we have configured everything necessary for our iOS APP.

In the case of Android:

  • Fill in all the requested data, package ID is the ID that appears in app.json > Android > package.
  • Choose an APP name, in my case, “APP Android”.
  • Now it generates a google-services.json file.
  • We have to add it to the root path of our project, just like we did with iOS.
  • Now, go back to our app.json file and add:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"android": {
"googleServicesFile": "./google-services.json",
}
"android": { "googleServicesFile": "./google-services.json", }
"android": {
    "googleServicesFile": "./google-services.json",
 }

Finally, we need to install this dependency:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npx expo install expo-build-properties
npx expo install expo-build-properties
npx expo install expo-build-properties

And add the following to app.json:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
"plugins":
"@react-native-firebase/app",
[
"expo-build-properties",
{
"ios": {
"useFrameworks": "static"
}
}
]
],
"plugins": "@react-native-firebase/app", [ "expo-build-properties", { "ios": { "useFrameworks": "static" } } ] ],
"plugins":
      "@react-native-firebase/app",
      [
        "expo-build-properties",
        {
          "ios": {
            "useFrameworks": "static"
          }
        }
      ]
      
    ],

Now we need to run the following command:
*IMPORTANT: This command deletes all the ios/android folders and regenerates them. If you have any configuration in these folders, you will have to re-add it or run the command without the –clean option

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
expo prebuild --clean
expo prebuild --clean
expo prebuild --clean

If you already have the generated folders and don’t want to delete their content, you can try this command:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
expo prebuild
expo prebuild
expo prebuild

Now let’s create the functionality to register the APP and receive PUSH notifications.

The first thing we need to do is add the Firebase library:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install @react-native-firebase/app --save
npm install @react-native-firebase/app --save
npm install @react-native-firebase/app --save

And Cloud Messaging:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
npm install @react-native-firebase/messaging --save
npm install @react-native-firebase/messaging --save
npm install @react-native-firebase/messaging --save

And update the iOS pod files:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cd ios
pod install
cd ios pod install
cd ios
pod install

*If running pod install gives an error due to the Firebase version, execute the following:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pod update Firebase/CoreOnly
pod update Firebase/CoreOnly
pod update Firebase/CoreOnly

Now, let’s create a component or screen to manage PUSH notifications. We call it Push Notifications.js and we are going to add the necessary notifications permission to use it on iOS:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React, { useState, useEffect } from "react";
import { StyleSheet, View } from "react-native";
import messaging from '@react-native-firebase/messaging';
async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
}
const Componente = (props) => {
const { } = props;
useEffect(() => {
requestUserPermission();
}, []);
return (
<View style={styles.contenedor} >
</View>
)
};
export default Componente;
import React, { useState, useEffect } from "react"; import { StyleSheet, View } from "react-native"; import messaging from '@react-native-firebase/messaging'; async function requestUserPermission() { const authStatus = await messaging().requestPermission(); const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL; if (enabled) { console.log('Authorization status:', authStatus); } } const Componente = (props) => { const { } = props; useEffect(() => { requestUserPermission(); }, []); return ( <View style={styles.contenedor} > </View> ) }; export default Componente;
import React, { useState, useEffect } from "react";
import { StyleSheet, View } from "react-native";

import messaging from '@react-native-firebase/messaging';

async function requestUserPermission() {
  const authStatus = await messaging().requestPermission();
  const enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;

  if (enabled) {
    console.log('Authorization status:', authStatus);
  }
}


const Componente = (props) => {

    const { } = props;

    useEffect(() => {
        requestUserPermission();
    }, []);

    return (
        <View style={styles.contenedor} >

        </View>
    )
};

export default Componente;

It would stay like this. In this way we will be able to request permissions to use notifications.

In Android, permissions are not needed to use notifications.

Now we are going to add code to get the device id that will allow us to send a message with the getToken() function;

What we’ll need to do here is get the device token and store it in a database along with the user ID. In this way in the back we can obtain it to send you PUSH notifications.

To get the device ID, we use the following:

import React, { useState, useEffect } from “react”;
import { StyleSheet, View, Platform } from “react-native”;

import messaging from ‘@react-native-firebase/messaging’;

async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;

if (enabled) {
console.log(‘Authorization status:’, authStatus);
//Obtener token:
const fcmToken = await messaging().getToken();
if (fcmToken) {
console.log(“Token: ” + fcmToken);
//enviarToken(fcmToken);
}
}
}

const Componente = (props) => {

const { } = props;

useEffect(() => {
if (Platform.OS === ‘ios’) {
requestUserPermission();
}else{
//Android
//Obtener token:
messaging().getToken().then(fcmToken => {
if (fcmToken) {
console.log(“Token: ” + fcmToken);
//enviarToken(fcmToken);
}
});
}

}, []);

return (
<View style={styles.contenedor} >

</View>
)
};

export default Componente;

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import React, { useState, useEffect } from "react";
import { StyleSheet, View, Platform } from "react-native";
import messaging from '@react-native-firebase/messaging';
async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
//Obtener token:
const fcmToken = await messaging().getToken();
if (fcmToken) {
console.log("Token: " + fcmToken);
//enviarToken(fcmToken);
}
}
}
const Componente = (props) => {
const { } = props;
useEffect(() => {
if (Platform.OS === 'ios') {
requestUserPermission();
}else{
//Android
//Obtener token:
messaging().getToken().then(fcmToken => {
if (fcmToken) {
console.log("Token: " + fcmToken);
//enviarToken(fcmToken);
}
});
}
}, []);
return (
<View style={styles.contenedor} >
</View>
)
};
export default Componente;
import React, { useState, useEffect } from "react"; import { StyleSheet, View, Platform } from "react-native"; import messaging from '@react-native-firebase/messaging'; async function requestUserPermission() { const authStatus = await messaging().requestPermission(); const enabled = authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL; if (enabled) { console.log('Authorization status:', authStatus); //Obtener token: const fcmToken = await messaging().getToken(); if (fcmToken) { console.log("Token: " + fcmToken); //enviarToken(fcmToken); } } } const Componente = (props) => { const { } = props; useEffect(() => { if (Platform.OS === 'ios') { requestUserPermission(); }else{ //Android //Obtener token: messaging().getToken().then(fcmToken => { if (fcmToken) { console.log("Token: " + fcmToken); //enviarToken(fcmToken); } }); } }, []); return ( <View style={styles.contenedor} > </View> ) }; export default Componente;
import React, { useState, useEffect } from "react";
import { StyleSheet, View, Platform } from "react-native";

import messaging from '@react-native-firebase/messaging';

async function requestUserPermission() {
    const authStatus = await messaging().requestPermission();
    const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
        console.log('Authorization status:', authStatus);
        //Obtener token:
        const fcmToken = await messaging().getToken();
        if (fcmToken) {
            console.log("Token: " + fcmToken);
            //enviarToken(fcmToken);
        }
    }
}

const Componente = (props) => {

    const { } = props;

    useEffect(() => {
        if (Platform.OS === 'ios') {
            requestUserPermission();
        }else{
            //Android
            //Obtener token:
            messaging().getToken().then(fcmToken => {
                if (fcmToken) {
                    console.log("Token: " + fcmToken);
                    //enviarToken(fcmToken);
                }
            });
        }
      
    }, []);

    return (
        <View style={styles.contenedor} >

        </View>
    )
};

export default Componente;

We have added an if to know if we are on Android/iOS, if it is on iOS we request the notification permissions and obtain the token we need to be able to receive messages on this device, in the case of Android, the token is obtained directly. We have to store this token on our server and associate it with the user to whom we want to send a notification.

The function sendToken(fcmToken) will take care of it (one way to implement it is to create a POST that sends that data to the server)

If you want to modify the icon in Android, you will have to add this in the manifest:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<meta-data tools:replace="android:resource"
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@mipmap/ic_notification" />
<meta-data tools:replace="android:value"
android:name="com.google.firebase.messaging.default_notification_color"
android:value="#efaf00" />
<meta-data tools:replace="android:value"
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="12345-canal_notificaciones"/>
<meta-data tools:replace="android:resource" android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_notification" /> <meta-data tools:replace="android:value" android:name="com.google.firebase.messaging.default_notification_color" android:value="#efaf00" /> <meta-data tools:replace="android:value" android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="12345-canal_notificaciones"/>
<meta-data  tools:replace="android:resource"
            android:name="com.google.firebase.messaging.default_notification_icon"
           android:resource="@mipmap/ic_notification" />

<meta-data  tools:replace="android:value"
           android:name="com.google.firebase.messaging.default_notification_color"
           android:value="#efaf00" />

<meta-data  tools:replace="android:value"
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="12345-canal_notificaciones"/>

The first two values ​​is for the icon and color. The last value is for the notifications channel.

0

Leave a Comment