Push Notification using Ionic 5 and Firebase Cloud Messaging

In this step by step tutorial, we will learn how to create and send push notifications from Firebase Cloud Messaging to Ionic app. We will use Ionic 5 Cordova native FCM plugin to receive push notification in an Ionic app.

Push Notification Example

A push notification is a message that shows up on a user’s mobile device. App owners can publish push notification at any time and send it to the user’s device.

Push notifications seem similar to SMS or text messages and mobile alerts. However, they only received by users who have installed your app. Almost every mobile platform supports push notifications such as iOS, Android, Fire OS, Windows, and BlackBerry.

Push notifications provide you updates, be it:

  • Latest offers to boost sales
  • Latest sports scores and news
  • Reports about traffic and weather
  • Flight check-in, change, and connection information

Table of Contents

  • Prerequisite
  • Firebase Setup for Android
  • Create Ionic 5 Push Notification App
  • Install & Configure Ionic Cordova Native FCM Plugin
  • Push Notification Implementation in Ionic 5 with Firebase
  • Sending and Receiving Push Notification
  • Conclusion

Prerequisite

To get started with this Ionic push notification tutorial, we must have the following tools, frameworks, and packages in our arsenal.

  • Latest Node
  • Ionic
  • Angular
  • Firebase FCM
  • Postman
  • Text Editor
  • Cordova
  • Ionic 5 Cordova Native FCM

If you do not have Node.js installed on your device then follow this tutorial on: How to Download and Install Node.js and npm

Firebase Setup for Android

To set up Firebase for Android, head over to console.firebase.google.com and create a Firebase project.

Firebase FCM Setup for Android

Next, a full-screen pop up appears on your screen, enter your project name in the input field and click on the continue button.

push notification in ionic

In the second screen, you will see Google analytics features you can enable them and click on the create project button.

Firebase Google Analytics Feautes

In the dashboard, you will have options to set up Firebase account for iOS, Android, Web, and Unity. Click on the Android button, and you will be redirected to the given screen.

Firebase Dashboard

Next, we will add Firebase to our Android app.

To register the app add the Android package name in the input field. For instance, we entered com.positronx.pushnotification then provided the app’s nickname (same as Ionic project name); however, its an optional value. Then click on the Register app button.

Next, you will see the following screen that allows you to Download the config file, which is used to run the mobile app in the Android Studio or emulator.

Click on the Download google-services.json file. We have to add this file to the based folder of our Ionic app.

Download Google Services JSON File

Click on the next button unless you reach to the last screen that can be skipped.

Run your app to verify installation

We have successfully created the Firebase application for Android platform.

Firebase application for Android platform

Create Ionic 5 Push Notification App

Make sure you have the latest version of Ionic CLI and Cordova globally installed on your device, if not use the below command.

sudo npm install -g cordova ionic

Check out the version of Ionic by running the following command.

ionic -v

# 5.4.15

Use command to update Ionic and Cordova.

sudo npm update -g cordova ionic

Run the following command to create a brand new blank Ionic 5 Firebase push notification app.

ionic start ionic-firebase-push-notification blank

Get inside the project folder.

cd ionic-firebase-push-notification

Run the following command in the terminal to install the lab plugin as a dev dependency.

npm install --save-dev @ionic/lab

Run the command to start the app in the browser, we can see app in iOS and Android mode.

ionic serve -l

Ionic 5 Firebase FCM Push Notification Example

Install & Configure Ionic 5 Cordova Native FCM Plugin

Now, we type the below command in the terminal to Install Google Firebase Cloud Messaging Cordova Push Plugin and Ionic Native FCM plugin.

ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated

FCM offers basic functionality for Firebase Cloud Messaging (FCM) and It supports iOS and Android.

npm install @ionic-native/fcm

Open your Ionic project and head over to the config.xml file. Here you can see the widget id “com.positronx.pushnotification” that carries the unique identification of your push notification app, here you have to add the package name that we defined in the Firebase.

Firebase Widget ID in config.xml

This time we will inject FCM service to enable the Push notification service in our Ionic app via Firebase FCM, go to app.module.ts file and add the following code in the main app module file.

// app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

// FCM
import { FCM } from '@ionic-native/fcm/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    FCM,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

export class AppModule {}

We imported FCM plugin and register in the providers array.

Push Notification Implementation in Ionic 4 with Firebase

Now, we will implement push notification in our Ionic 4 Cordova app through Firebase Cloud Messaging.

Place the following code in the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { FCM } from '@ionic-native/fcm/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})

export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private fcm: FCM
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      // subscribe to a topic
      // this.fcm.subscribeToTopic('Deals');

      // get FCM token
      this.fcm.getToken().then(token => {
        console.log(token);
      });

      // ionic push notification example
      this.fcm.onNotification().subscribe(data => {
        console.log(data);
        if (data.wasTapped) {
          console.log('Received in background');
        } else {
          console.log('Received in foreground');
        }
      });      

      // refresh the FCM token
      this.fcm.onTokenRefresh().subscribe(token => {
        console.log(token);
      });

      // unsubscribe from a topic
      // this.fcm.unsubscribeFromTopic('offers');

    });
  }
}

We imported FCM API from ‘@ionic-native/fcm/ngx’ and Router from ‘@angular/router’.

Inject FCM and Router services in the constructor.

We can access to subscribeToTopic method via FCM package and subscribe to a topic, the subscribeToTopic() takes the topic name as a parameter.

The fcm.getToken() method returns a token of a push notification, and we are showing the token in the console.

The fcm.onNotification() method returns a push notification from Firebase Cloud Messaging.

The fcm.onTokenRefresh() method allows refreshing the Firebase Cloud Messaging (FCM) token.

Use unsubscribeFromTopic() method to unsubscribe from a topic from FCM.

Sending and Receiving Push Notification in Ionic 4 via FCM

In this step, we will create the project build; let’s run the below command to add the Android platform in Ionic app.

ionic cordova platform add android

In this step, we will add the google-services.json in the root of our project and also inside the platform/android folder file that we downloaded from Firebase FCM. This step is crucial, and it makes communication between the Ionic app and Firebase.

Add google-services.json in Ionic 5

Run the Ionic app in the Android device by using the following command.

ionic cordova run android --livereload

We used the --livereload tag. It automatically creates the build as soon as it noticed any change in the application files.

Firebase Cloud Messaging Example

Go to your Firebase dashboard click on Grow > Cloud Messaging, we define Firebase Notification here, add the notification title, text even you can pass the notification image here.

Click on the ‘Send test message’ button, and it will open a popup where you have to define the Firebase Cloud Messaging token to send push notification to the Ionic app.

Ionic 5 Firebase Send Push Notification Example

Type chrome://inspect in the address bar, then select the inspect mode there you can see the Firebase push notification token that we will need in the next step.

FCM notification token

We have done all the formalities, and now we will hit on the Test button to send a test notification.

Sending and Receiving Push Notification in Ionic 5

Conclusion

The Ionic 5 Firebase FCM Push Notification Tutorial is over; in this tutorial, we have learned how to send push notifications from Firebase and receive notification in an Ionic app.

You can get the complete code of this tutorial on this GitHub repository.

#ionic #firebase #mobile-apps

Push Notification using Ionic 5 and Firebase Cloud Messaging
17.45 GEEK