Push Notification using Ionic 4 and Firebase Cloud Messaging

by Didin J. on Feb 20, 2019 Push Notification using Ionic 4 and Firebase Cloud Messaging

The comprehensive step by step tutorial on receiving a push notification on Mobile App using Ionic 4 and Firebase Cloud Messaging (FCM)

The comprehensive step by step tutorial on receiving a push notification on Mobile App using Ionic 4 and Firebase Cloud Messaging (FCM). We will use Ionic 4 Cordova native FCM plugin for receiving a push notification and using Firebase API for sending push notification from the Postman. A few years back, we have created a tutorial on receiving push notification using Firebase Cloud Messaging with Ionic 2.


Shortcut to the steps:


Google said that notification is a message that pops up on the user's device. Notifications can be triggered locally by an open application, or they can be "pushed" from the server to the user even when the app is not running. They allow your users to opt-in to timely updates and allow you to effectively re-engage users with customized content. In this tutorial, the message sent from the Firebase via API using Postman. Then receive by Ionic 4 mobile apps using Ionic Cordova Native FCM plugin.

The following tools, frameworks, and modules are required for this tutorial:

Before going to the main steps, we assume that you have to install Node.js. Next, upgrade or install new Ionic 4 CLI by open the terminal or Node command line then type this command.

sudo npm install -g ionic

You will get the latest Ionic CLI in your terminal or command line. Check the version by type this command.

ionic --version
4.10.3

You watch the video version of this tutorial on our YouTube channel.


Setup and Configure Google Firebase Cloud Messaging (FCM)

We are using Firebase Cloud Messaging (FCM) because it's a cross-platform messaging solution that lets you reliably deliver messages at no cost. Open your browser then go to Google Firebase Console then log in using your Google account.

Push Notification using Ionic 4 and Firebase Cloud Messaging - Firebase Welcome

Next, click on the Add Project button then fill the Project Name with `Ionic 4 FCM` and check the terms then click Create Project button.

Push Notification using Ionic 4 and Firebase Cloud Messaging - Firebase Add Project

After clicking the continue button you will redirect to the Project Dashboard page. Click the Gear button on the right of Project Overview then click Project Settings. Click the Cloud Messaging tab the write down the Server Key and Sender ID for next usage in the API and Ionic 4 App. Next, back to the General tab then click the Android icon in your Apps to add Android App.

Push Notification using Ionic 4 and Firebase Cloud Messaging - Firebase Add Android App

Fill the required fields in the form as above then click Register App button. Next, download the `google-services.json` that will use in the Ionic 4 app later. Click next after download, you can skip Add Firebase SDK by click again Next button. You can skip step 4 if there's no App creating on running yet.


Create a new Ionic 4 App

As usual, we will create a blank Ionic 4 as a starter step. To create a new Ionic 4 App, type this command in your terminal.

ionic start ionic4-push blank --type=angular

If you see this question, just type `N` for because we will installing or adding Cordova later.

Install the free Ionic Appflow SDK and connect your app? (Y/n) N

Next, go to the newly created app folder.

cd ./ionic4-push

As usual, run the Ionic 4 App for the first time, but before run as `lab` mode, type this command to install `@ionic/lab`.

npm install --save-dev @ionic/lab
ionic serve -l

Now, open the browser and you will the Ionic 4 App with the iOS, Android, or Windows view. If you see a normal Ionic 4 blank application, that's mean you ready to go to the next steps.

Push Notification using Ionic 4 and Firebase Cloud Messaging - Ionic 4 Blank


Add Ionic 4 Cordova Native FCM Plugin

We will use the latest Google Firebase Cloud Messaging Cordova Push Plugin that also available as an Ionic module. To install Ionic 4 Cordova Native Firebase Message Plugin, type this command.

ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated
npm install @ionic-native/fcm

Next, open and edit `src/app/app.module.ts` then add this import of @ionic-native/fcm/ngx.

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

Add FCM module to `@NgModule` providers.

providers: [
  StatusBar,
  SplashScreen,
  FCM,
  { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],

Next, open and edit `src/app/app.component.ts` then add these imports of FCM (@ionic-native/fcm/ngx) and Router (@angular/router).

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

Inject FCM and Router module to the constructor along with other required modules.

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

Inside platform ready of `initializeApp` function, add a function to get FCM token then print out to the browser console.

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

Add this function to refresh the FCM token.

this.fcm.onTokenRefresh().subscribe(token => {
  console.log(token);
});

Add this function to receive a push notification from Firebase Cloud Messaging (FCM).

this.fcm.onNotification().subscribe(data => {
  console.log(data);
  if (data.wasTapped) {
    console.log('Received in background');
    this.router.navigate([data.landing_page, data.price]);
  } else {
    console.log('Received in foreground');
    this.router.navigate([data.landing_page, data.price]);
  }
});

Above an example of receiving a push notification from FCM will redirect to the other page with params of data. For that, next, we have to add a new page by type this command.

ionic g page second

Next, modify `src/app/app-routing.module.ts` then change the new page route.

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'second/:price', loadChildren: './second/second.module#SecondPageModule' },
];

Next, open and edit `src/app/second/second.page.ts` then add this import of ActivatedRoute (@angular/router).

import { ActivatedRoute } from '@angular/router';

Inject the ActivateRoute module to the constructor.

constructor(private route: ActivatedRoute) { }

Add a variable for hold data from router parameters.

price: any = '';

Add this line to get data from the router parameters.

constructor(private route: ActivatedRoute) {
  this.price = this.route.snapshot.params['price'];
}

Next, open and edit `src/app/second/second.page.html` then replace all HTML tags with this simple page that shows the simple text.

<ion-header>
  <ion-toolbar>
    <ion-title>Second</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-card>
    <ion-card-header>
      <ion-card-title>Congratulation!</ion-card-title>
    </ion-card-header>

    <ion-card-content>
      You get price from our sponsor:
      <h2>{{price}}</h2>
    </ion-card-content>
  </ion-card>
</ion-content>

If you plan to send push notification to the group of the topic, add these lines inside the platform ready.

this.fcm.subscribeToTopic('people');

To unsubscribe from the topic, add this line.

this.fcm.unsubscribeFromTopic('marketing');


Run and Test Sending and Receiving Push Notification

Before running this Ionic 4 app, we have to copy the downloaded `google-services.json` file to the root of the project. Type this command to add the Android platform.

ionic cordova platform add android

Next, copy the `google-services.json` to the `platform/android/` directory.

cp google-services.json platform/android/

Next, run the Ionic 4 App to the Android device by type this command.

ionic cordova run android

After the app running on the device, check the console from the Google Chrome by type this address `chrome://inspect` then choose the inspect link. You should take to the browser inspector, just change to the console tab.

Push Notification using Ionic 4 and Firebase Cloud Messaging - Chrome Console

As you can see above, you can take and write down the FCM token for use by Postman. Next, open the Postman application from your computer. Change the method to POST and add this address `https://fcm.googleapis.com/fcm/send`. On the headers, add this key `Content-Type` with value `application/json` and `Authorization` with value `key=YOUR_FIREBASE_KEY...`.

Push Notification using Ionic 4 and Firebase Cloud Messaging - Postman Headers

Next, add this JSON data to the RAW body.

{
  "notification":{
    "title":"Ionic 4 Notification",
    "body":"This notification sent from POSTMAN using Firebase HTTP protocol",
    "sound":"default",
    "click_action":"FCM_PLUGIN_ACTIVITY",
    "icon":"fcm_push_icon"
  },
  "data":{
    "landing_page":"second",
    "price":"$3,000.00"
  },
    "to":"eadego-nig0:APA91bEtKx9hv50lmQmfzl-bSDdsZyTQ4RkelInfzxrPcZjJaSgDmok3-WQKV5FBu9hrMrkRrcCmf3arkGSviGltg5CyC2F9x1J2m0W7U8PxJ3Zlh7-_tL6VcFdb76hbaLIdZ-dOK15r",
    "priority":"high",
    "restricted_package_name":""
}

If you want to send by topics recipients, change the value of `to` to `topics/people`. Next, click the send button and you should see this response.

{
    "multicast_id": 7712395953543412819,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1550632139317442%b73443ccb73443cc"
        }
    ]
}

And you will see the notification on your Android device background screen.

Push Notification using Ionic 4 and Firebase Cloud Messaging - Push Notification

If you tap on it, it will open the App and redirect to the second page with this view.

Push Notification using Ionic 4 and Firebase Cloud Messaging - Ionic 4 Second Page

That it's, the example of receiving push notification using Ionic 4 and Firebase Cloud Messaging. You can grab the full source code from our GitHub.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can take the following cheap course:

Thanks!