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

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

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

Add Custom Checkbox on UITableViewCell or UITableView in Swift 4

Add Custom Checkbox Introduction to how to add custom checkbox on UITableViewCell or UITableView in swift 4 In this tutorial, we are going to learn about how can we create or add custom checkbox on UITableViewCell or UITableView in swift and perform IBAction on our custom checkbox placed on UITableViewCell or UITableView in swift 4. We will place UIButton on UITableViewCell that will act as checkbox for our UITableViewCell in UITableView using swift 4. In the end of this tutorial, we will have output as shown in below picture Learn how to create checkbox in swift from  HERE Steps to create or add custom checkbox on UITableViewCell or UITableView Step 1 :  Create a new Xcode project and select  "Single View App"  template. Name  project as  "addCheckBoxonTable-Tutorial" . Step 2:  Open  "Main.storyboard"  file and drag UITableView object on to the view. Then we will add constraints to UITableView so that it fits...