September 28, 2022

Robotic Notes

All technology News

Mobile push notifications with Firebase

11 min read


Push notifications are messages to users to build audience relationships and get users back into the mobile app. In this article, you will learn how to set this feature up in React Native with Firebase. I will be using a simple app, and on that app, I will add the push notification functionality for Android and iOS.

You can also get the source code for this tutorial already on Github.. To follow up with this tutorial:

  • you need a Google account
  • you should be familiar with React Native, which we’ll use to write our app
  • For Android, you need an Android emulator, which will be used to test the push notification. You can find out how to install React Native and set up the emulators here.
  • For iOS, Xcode should be set up. An Apple developer account is necessary to enable this push notification feature in the iOS App. An iOS emulator should be set up for testing the iOS application. Still, an actual iOS device must be available to test the push notifications as they won’t be delivered on an iOS emulator. You can also learn how to set up an emulator here.

Creating our React Native project

First, you will need to initiate a React Native project. Run the following command.

1npx react-native init pushnotificationtest && cd pushnotificationtest

Running this operation will create a React Native project and install a template in the pushnotificationtest folder and then navigate the terminal into the folder. You can now open that folder in your code editor. We will create a simple UI where we will land when our app is opened, so to do that, we edit the App.js file with the code below:

1import React from 'react';

2import type {Node} from 'react';

3import { SafeAreaView, ScrollView, StatusBar, StyleSheet, Text, useColorScheme, View,} from 'react-native';

4import { Colors, Header,} from 'react-native/Libraries/NewAppScreen';

5const Section = ({children, title}): Node => {

6 const isDarkMode = useColorScheme() === 'dark';

7 return (

8 <View style={styles.sectionContainer}>

9 <Text style={[ styles.sectionTitle, { color: isDarkMode ? Colors.white : Colors.black, }, ]}> {title} </Text>

10 <Text style={[ styles.sectionDescription, { color: isDarkMode ? Colors.light : Colors.dark, },]}> {children} </Text>

11 </View>

12 );

13};

14

15class App extends React.Component {

16render () {

17 return (

18 <SafeAreaView>

19 <StatusBar barStyle={'light-content', 'dark-content'} />

20 <ScrollView contentInsetAdjustmentBehavior="automatic">

21 <Header />

22 <View style={{ backgroundColor: Colors.white, }}>

23 <Section title="Welcome">This is a simple <Text style={styles.highlight}> App Interface</Text> to test our Push notification App.

24 </Section>

25 </View>

26 </ScrollView>

27 </SafeAreaView>);

28 };

29};

30export default App;

Adding the code above renders the UI of the app but will crash because some styles have been declared on there but are not added yet. Therefore, you should add the following code above the export default app statement.

1const styles = StyleSheet.create({

2 sectionContainer: {

3 marginTop: 32,

4 paddingHorizontal: 24,

5 },

6 sectionTitle: {

7 fontSize: 24,

8 fontWeight: '600',

9 },

10 sectionDescription: {

11 marginTop: 8,

12 fontSize: 18,

13 fontWeight: '400',

14 },

15 highlight: {

16 fontWeight: '700',

17 },

18});

You can now compile and run your app on the emulators. To run the app on Android, you will run:

1npx react-native run-android

Once the Android Emulator has started and rendered the app, we will compile and run the iOS Emulator.

1npx react-native run-ios

After a successful build, you should have iOS and Android displays like this:

1-2

Now that you have the UI set, let’s take the next step to set up push notifications.

Setting up Firebase

We will be using Firebase Cloud Messaging to set up push notifications hence the importance of linking our app with Firebase Console. You can open up your browser and follow the link to Firebase Console, Get Started, and log in with your Google account. Then, you should land on a page like this on which you should click Create a Project.

3

To create a Project, you need to input the Project name of which I am using pushnotificationtest. Then, continue.

4

On the next screen, you can Enable Google Analytics and click continue. After that, you will be directed to select an analytics account on the final screen. Select an account and click Create Project. Once your project is successfully created, you will get to a screen like this:

5

Adding the Android app to the Firebase project

You need to add the Android and iOS React Native Project to the Firebase project. To add the Android app to the project, click on the Android logo there; it will take you to a screen like this:

6

So to add the Android App to the project, the first is to add the Android Package Name. The Android Package name is on default when the app is being created; therefore, you should go over to the project and grab it from the AndroidManifest.xml file, which is located at Android/app/src/main/androidmanifest.xml, and on the top of the document, you will find the package name.

7

Copy the package name to the console. Add a nickname to the app. I used Android Push Notification as my nickname. Leave the SHA-1 field blank and continue. On the following screen, download the google-services.json file and copy it to the Android/App directory for the project.

8

Next, you will find some dependencies and plugins to link the app with Firebase. Copy the following dependency and add it to the dependencies block in the build.gradle file in the pushnotificationtest/Android directory:

1classpath 'com.google.gms:google-services:4.3.10'

Then to the build.grade file in the pushnotificationtest/Android/App, add this plugin at the top of the page, directly under the com.android.application line.

1apply plugin: 'com.google.gms.google-services'

After that is set, return to the console, click Next, and then Continue to Console. You have just created your Android App on the Firebase project and linked it to the React Native project. Next, you need to Add the iOS App.

Adding the iOS app to the Firebase project

Navigate to the dashboard and click on the iOS icon to Add the iOS App. You should be brought to this page.

9

Here’s where you need to add the Apple Bundle ID. It is also generated at the creation of the project, but you can register a new one if you don’t want the default one. I set it to com.mynewproject.pushnotificationtest for this project. To get the default Apple Bundle ID, open your Xcode by running the command below from your terminal.

1cd ios && open pushnotificationtest.xcworkspace

Once Xcode is open, click on the name of the project, and on the screen, you will see the bundle ID on the other side.

10

Now, copy it to the Apple bundle ID field above and add the set nickname for the app. You can leave your Apple Store ID for now and click next. Leave out downloading GoogleService-Info.plist for now and continue. Now we need to add the Firebase SDK, and just like it’s stated in the documentation, you need to navigate back to Xcode, open your AppDelegate.mm file, and add the following at the top of the file to import the Firebase SDK:

1#import <Firebase.h>

Then, within your didFinishLaunchingWithOptions method, add the following to the top of the method:

1- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

2 // Add only this below \

3 [FIRApp configure];

Return to the browser, then click next and Continue to Console. iOS requires you to enable push notifications on the app. You will need to add push notification capacity to the app to achieve this. Then, on the Apple Developer Account, you will need to generate an APN (Apple Push Notification) key that you will add to the cloud messaging area on Firebase to complete the linking of the iOS App to Firebase. Now, you should open up Xcode and select the right team on which you are registering the app.

11

Next, click on add + Capability and scroll down to find Background Modes. Double click on that and select the Background Fetch and Remote Notifications options.

12

After that, click on the + Capability again and scroll to find Push Notifications. Double click on it also. Next, log in to your developer account and click on the Certificates, Identifiers, and Profile section.

13

Click on Identifiers from the menu on the left. Now, look for the bundle ID of your app. Once you find it, click to open it. Once it’s open, under capabilities, scroll down and ensure Push Notifications is checked. Next, return to the previous page and select Keys among the menu items on the left.

14

Click on the + icon next to Keys and add a key name. For this project, I used PushNotificationTest. Then, check the box for Apple Push Notification Service and continue. On the next page, click on Register and then download the key. Endeavor to copy the Key ID.

15

Go back to the Firebase Console and click on the iOS App settings. From the Tabs, click on Cloud Messaging,

16

Scroll down to iOS App Configuration and under the APNs Authentication Key, click on upload.

17

Paste the Key ID you copied into the Key ID field, then click on the browser from which you should add the key that you generated and downloaded from your Apple Developer Account.

18

You may also need to add your Apple Developer Team ID. You can grab it from your Apple Developer Dashboard. Then upload. After this upload, navigate to General among the Tabs, scroll down and under the Your Apps section, click on GoogleService-Info.plist to download it.

19

Once it’s downloaded, go to Xcode, right-click on the project name, and select add file to project. A dialogue box should open where you should grab the GoogleService-Info.plist file and ensure that ”Copy items if needed” is selected, then click Add. Since you have successfully added the iOS Apps to your console, you can move on to add the push notification functionality on our app.

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

replayer.png

Start enjoying your debugging experience – start using OpenReplay for free.

Adding Push Notification Functionality

Now, you need to add the push notification functionality to the app. Moving forward, we will get back to the terminal. Please ensure you are in the root folder, the pushnotificationtest folder. You will need to install some dependencies: Firebase Core and Firebase Messaging. Key in the command below to perform the installation.

1npm install @react-native-firebase/app && @react-native-firebase/messaging

Then go back to the terminal and key in the following command.

1cd ios && pod install && cd ..

The above command will install all the necessary files for the iOS push notification to work. You need to add some code to the index.js and the app.js in the root folder. The code you will be adding is for receiving the push notification and handling it both in the background and foreground state. You should start by adding some import statements to the index.js file to import the necessary modules before the code.

1import React from 'react';

2 import messaging from '@react-native-firebase/messaging';

After that, you should add the code to invoke the setBackgroundMessageHandler method to define the background message handler. You will simply console.log() the received message in the handler. This piece of code should be added after the import statements.

1messaging().setBackgroundMessageHandler(async remoteMessage => {

2 console.log('Message is handled in the background!', remoteMessage);

3});

Following that, you should set the isHeadless function and return to the app. This isHeadless parameter will only be true if the app is started by iOS when the Push Notification arrives. On Android, this parameter will be undefined. Add the function after the previous piece of code.

1function HeadlessCheck({ isHeadless }) {

2 if (isHeadless) {

3 console.log('App launched by iOS in background, ignore it' );

4

5 return null;

6 }

7 return <App />;

8}

9AppRegistry.registerComponent(appName, () => HeadlessCheck)

Next, in the App.js file, you should import the messaging module by adding the import statement below among the imports at the top of the page.

1import messaging from '@react-native-firebase/messaging'

Below is a piece of code to check for permission and request user permission to receive push notifications on the app. For iOS, the user has to allow permission before it is delivered to them, but for Android, it will always return permission granted. After checking the permissions, to get the unique device token which is the address the FCM uses to send notifications to individual devices, you will need to add the getToken method as shown. You will also notice the onTokenRefresh handler. This method is basically to get the new token of a device whose token has changed. You need to define the onMessage handler to handle the received notification when the app is running in the foreground.

1componentDidMount(){

2 messaging()

3 .requestPermission()

4 .then(authStatus => {

5console.log('APNs Status: ', authStatus);

6

7if (authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus == messaging.AuthorizationStatus.PROVISIONAL) {

8 messaging()

9 .getToken()

10 .then(token => {

11 console.log('messaging.getToken: ', token);

12 });

13 messaging().onTokenRefresh(token => {

14 console.log('messaging.onTokenRefresh: ', token)

15 });

16 fcmUnsubscribe = messaging().onMessage(async remoteMessage => {

17 Alert.alert(

18 remoteMessage.notification.title,

19 remoteMessage.notification.body)

20 });

21}

22})

23 .catch(err => {

24console.log('messaging.requestPermission Error: ', err);

25 });

26}

This line of code is used to declare the fcmUnsubscribe variable null until the app runs. It should be added at the top of the page, right after the imports.

1var fcmUnsubscribe = null

Based on the code, when the app runs in the foreground, it will display the notification using an alert, but when it’s in the background, you will find the notification in the notification pane of the device. After adding all the codes above, send a test Push Notification.

Sending a Test Push Notification

Before sending a test push notification, you must first build the app. Use the commands stated above to run the Android app. For iOS, connect your actual device to use it, then state the name of the device when building the iOS App as such:

1npx react-native run-ios "Name of Device"

Once your Android and iOS apps have been built into the app, navigate to the Firebase console as we will be sending push notifications from the console. From the menu items on the left, scroll to the Engage section, and under it, click on Messaging.

20

On the dashboard, click on Send your first message. It will land you on a page where you must compose your notification.

21

Now, you need to add your notification title, text, and image just like I’ve done, then click next.

22

Here, add your Android and iOS apps as targets to receive this notification, then click next. Set a schedule for now and ignore the analytics fields, and click next. Ignore the data fields and enable sound. You can leave the badge area to be disabled.

23

You can then click review and submit. The notification displays as an Alert when the app is in the foreground state, and when it’s in the background state, it stays in the device’s notification area. Here’s an example for Android.

24

25

On iOS, this is the output:

26

If you followed this tutorial, you should receive a push notification as shown above on your Android emulator and your iOS device.

Conclusion

Push Notifications is an exciting feature that can be used to engage app users on iOS and on Android. With React Native, we can easily set that functionality for our apps as we’ve just done. I hope you found this tutorial educational!

newsletter



Source link