Skip to main content

React Native Push Notifications with Firebase & Hooks 2023

React Native Push Notifications with Firebase & Hooks 2023

Study app for implementing Push Notifications with Firebase in a React Native mobile app.

In this tutorial we are going to implement Push Notifications in a React Native mobile application, our notification backend will be in Firebase for ease of use, but you can use your own system.

You can find the complete code here: https://github.com/uokesita/RNPushNotifications

First, create a project in your Google Firebase Console https://console.firebase.google.com/

Also, create your React Native project and enter its directory
react-native init RNPushNotifications

Adding Firebase to your app

Register your app in Firebase and follow the configuration steps for Android and for iOS.
Download your GoogleService-Info.plist and google-services.json. Don’t forget to place them in the correct folder for each platform.

Android
iOS

Add and link the React Native Firebase package to your app.

yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging
cd ios ; pod install ; cd ..

Follow the installation instruction for the latest release here:

Android: https://rnfirebase.io/#2-android-setup
iOS: https://rnfirebase.io/#3-ios-setup

Generate APNS certificate for iOS Push Notifications

On iOS, you need to generate an APNs certificate to receive Push Notifications.
Apple Push Notification Service (commonly referred to as Apple Notification Service or APNs) is a platform service created by Apple Inc. that enables third-party application developers to send push notifications to iOS users. You must have a paid Apple Developer account to create certificates.

  • Log in to Apple developer account and click “Certificates, IDs & Profiles”
    (https://developer.apple.com/)
  • Select “Identifiers” from the left menu
Click the Plus (+) sign above the center list
Choose “App IDs” from the selection options
Fill out your Description, Bundle ID, and choose “Push Notifications” from the options.
Confirm your information and click “Register”

Generate a Certificate from Keychain Access

  • Launch the Keychain Access application in your Mac OS X and Select Keychain Access -> Certificate Assistant -> Request a Certificate From a Certificate Authority
  • Enter the email address and check the ‘Saved to disk’ option, then click Continue

Generate a Development Certificate

  • Go back to the developer account and select app from App IDs and click on it to Edit
  • Scroll Down to Push Notifications and click on Configure
  • Under Development SSL Certificate, click Create Certificate
  • Choose the file you created in the previous step and click Continue
  • Download Development Certificate to finish process

Generate APNs .p12 certificate

Double click Development certificate generated in the previous step to add it to Keychain Access. Go to Keychain Access, select login keychain and My Certificate from the side menu. Find the app certificate and right-click to export it.

Enter certificate name and click Save
Enter the password for certificate and click OK/Enter your computer admin password to finish the process

As pointed by a nice commenter (Andrew Vo-Nguyen) you also need to add your .p12 certificate to Firebase > Project Settings > Cloud Messaging (Tab) > iOS app configuration > APNs Certificates. Thanks, Andrew.

These are all the steps to create a development certificate, now we continue to add push notifications to our app.

Configuration iOS project

On Xcode go to your project settings, under Singing and Capabilities, add these two:

Push notifications
Background Modes — Check only Remote Notifications

iOS prevents messages from containing notification (or 'alert') payloads from being displayed unless you have received explicit permission from the user.

This module provides a requestPermission method which triggers a native permission dialog requesting the user's permission:

import messaging from '@react-native-firebase/messaging';
...
useEffect(() => {
requestUserPermission();
}, []);

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

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

The permissions API for iOS provides much more fine-grain control over permissions and how they're handled within your application. To learn more, view the advanced iOS Permissions documentation.

On Android, you do not need to request user permission. This method can still be called on Android devices; however, and will always resolve successfully.

Implementing FCM tokens in your app

Let’s go to our App.js and add some code

After everything set up and configured for the Android and iOS (in Xcode), now, we have to implement the FCM push notification in React Native side using React Native Firebase module. Just open and edit App.js then add or modify these imports of Firebase, React Hooks useEffect, and React Native Alert.

import React, {Fragment,useEffect} from "react";
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Alert
} from "react-native";
import firebase from "react-native-firebase";

Change the method that runs checks Permissions.

requestUserPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
getFcmToken() //<---- Add this
console.log('Authorization status:', authStatus);
}
}

Add a function to get FCM token from the Firebase and show the token to the React Native Alert.

getFcmToken = async () => {
const fcmToken = await messaging().getToken();
if (fcmToken) {
console.log(fcmToken);
console.log("Your Firebase Token is:", fcmToken);
}
else {
console.log("Failed", "No token received");
}
}

After having configured everything correctly, we can test directly from the Firebase console:

  • Go to the Cloud Messaging option in the left pane.
  • Click on Send your first message
  • Enter your test text, select the Android application to which you want to send the application, and click Send.

You can use the FCM token to test your notifications.

In the console, you will see the FCM token, you can copy and paste it in the Firebase Console for your testings


1) To receive notifications in the Android notifications bar, you must have setup a Google Account in the emulator.
2) When the app is active, in foreground mode, the notification won’t show in notifications bar. When the app is running in background or not active, notification will show there! https://i.imgur.com/dX4IGOt.jpg

Other functions

Foreground state messages

To listen to messages in the foreground, call the onMessage method inside your application code. Code executed via this handler has access to React context and is able to interact with your application (e.g. updating the state or UI).

For example, the React Native Alert API could be used to display a new Alert each time a message is delivered.

import { Alert } from 'react-native';
...
useEffect(() => {
requestUserPermission();
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
return unsubscribe;
}, []);
...

The remoteMessage property contains all the information about the message sent to the device from FCM, including any custom data (via the data property) and notification data. To learn more, view the RemoteMessage API reference.

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.

Please see the uses for background notifications here
https://rnfirebase.io/messaging/usage#foreground-state-messages

Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...