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

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

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