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

Master Map & Filter, Javascript’s Most Powerful Array Functions

Master Map & Filter, Javascript’s Most Powerful Array Functions Learn how Array.map and Array.filter work by writing them yourself This article is for those who have written a  for  loop before, but don’t quite understand how  Array.map  or  Array.filter  work. You should also be able to write a basic function. By the end of this, you’ll have a complete understanding of both functions, because you’ll have seen how they’re written. Array.map Array.map  is meant to transform one array into another by performing some operation on each of its values. The original array is left untouched and the function returns a new, transformed array. For example, say we have an array of numbers and we want to  multiply each number by three . We also don’t want to change the original array. To do this without  Array.map , we can use a standard for-loop. for-loop var originalArr = [1, 2, 3, 4, 5]; var newArr = []; for(var i = 0; i < originalArr.length; i+...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...