Skip to main content

Receiving push notification from Firebase in React Native

Receiving push notification from Firebase in React Native

Registering the app

To use the FCM, we must create a new Firebase project or use an existing one. Creating a new Firebase project is done by navigating to the Firebase Console.

click on Create project.

Registering a new Android app

React Native Firebase

To connect our React Native app to the apps created in the Firebase console, a couple of steps are required. Let’s say we already have our React Native app created. All that we’re missing now are the libraries which we’ll use to implement push notifications. The first thing to do is to add the required Firebase libraries to the project:

yarn add react-native-push-notification
yarn add @react-native-community/push-notification-ios
yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging

Once the Firebase libraries have been added, we need to do a bit more setup to be able to successfully receive push notifications on both Android and iOS devices.

Android setup

Gradle setup Android app

Go to android > app > build.gradle & search applicationId. That’s like “com.appName

copy & pest on Android package name. & click on Register App button.

To enable push notifications on Android, we have to download the config file google-services.json generated by Firebase previously and place it in the android/app/ folder.

Now open android > app > build.gradle file & put

apply plugin: ‘com.google.gms.google-services’ // apply after this line on top & Inside dependencies put this one line

Use this Code :

dependencies {// For React Native Push Notification
implementation project(‘:react-native-push-notification’)
}

At android > build.gradle

supportLibVersion = “29.0.0”
playServicesVersion = “17.0.0”
googlePlayServicesVersion = “+” // default: “+”
firebaseMessagingVersion = “21.1.0”
firebaseVersion = “17.3.4”

iOS setup

That is done by downloading the GoogleService-Info.plist file from our iOS Firebase project

To allow Firebase to use these credentials, we need to add a few lines in our ios/{projectname}/appDelegate.m file. Firstly, we need to add a line to the top of the file to import Firebase SDK:

#import <Firebase.h>

After that, we add the following inside the existing didFinishLaunchingWithOptions method:

Use this Code :

// ADD THIS LIBRARY IN TOP
#import <Firebase.h>
#import <RNCPushNotificationIOS.h>
#import <UserNotifications/UserNotifications.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[FIRApp configure]; // ADD THIS
// ...
}
// ADD THIS Functions// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
[RNCPushNotificationIOS didReceiveNotificationResponse:response];
}
//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}

One more necessary step to enable push notifications for the iOS project is to go to the project in Xcode, pick Signing and Capabilities under project settings and add Push Notifications as well as Background Modes with boxes checked as shown below.

Receiving messages from Firebase

After setting up everything required for push notifications to work on both platforms, what’s left is to write our React Native code for receiving messages from Firebase, which will later be shown as notifications.

For the purpose of this blog post, we’ll be sending the messages directly from the Firebase console. It allows us to choose the title and text of the notification, as well as a custom image, scheduling for a later date and other useful features.

It also requires a mandatory Android property called senderID. This can be fetched form Project Settings > Cloud Messaging.

Select GCM or FCM Sender ID
import React, { useEffect } from 'react'
import PushNotification from 'react-native-push-notification'
const RemotePushController = () => {
useEffect(() => {
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log('TOKEN:', token)
},
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log('REMOTE NOTIFICATION ==>', notification)
// process the notification here
},
// Android only: GCM or FCM Sender ID
senderID: '25620000662',
popInitialNotification: true,
requestPermissions: true
})
}, [])
return null
}
export default RemotePushController

Add this method inside the App.js file as shown below:

// after other import statements
import RemotePushController from './src/services/RemotePushController'
// before the ending <View>
<RemotePushController />
</View>

To test it out, go to Cloud Messaging section and compose a notification.

Click the button Send test message. You got notification.

Always motivate to find new things in react native

Sanjay Vaghasiya (Sr. React Native | iOS Developer).

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