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

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 = { ...

An introduction to Size Classes for Xcode 8

Introduction to Size Classes for Xcode In iOS 8, Apple introduced  size classes , a way to describe any device in any orientation. Size classes rely heavily on auto layout. Until iOS 8, you could escape auto layout. IN iOS8, Apple changed several UIKit classes to depend on size classes. Modal views, popovers, split views, and image assets directly use size classes to determine how to display an image. Identical code to present a popover on an iPad  causes a iPhone to present a modal view. Different Size Classes There are two sizes for size classes:  compact , and  regular . Sometime you’ll hear about any.  Any  is the generic size that works with anything. The default Xcode layout, is  width:any height:any . This layout is for all cases. The Horizontal and vertical dimensions are called  traits , and can be accessed in code from an instance of  UITraitCollection . The  compact  size descr...

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...