Ionic 4 Firebase FCM Push Notification Tutorial with Example - positronX.io

Ionic 4 Firebase FCM Push Notification Tutorial with Example - positronX.io

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 4 Cordova native FCM plugin to receive push notification in an Ionic 4 app. A push notification is a message that shows up on a user’s mobile device. …

Push Notifications with Ionic 4 and Firebase Cloud Messaging

Push Notifications with Ionic 4 and Firebase Cloud Messaging

Learn how to create and send push notifications from Firebase Cloud Messaging to Ionic app. We will use Ionic 4 Cordova native FCM plugin to receive push notification in an Ionic 4 app. Learn how to send push notifications from Firebase and receive notification in an Ionic app.

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 4 Cordova native FCM plugin to receive push notification in an Ionic 4 app.

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
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 4
  • Angular 8
  • Firebase FCM
  • Postman
  • Text Editor
  • Cordova
  • Ionic 4 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.

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

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

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.

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.

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

We have successfully created the Firebase application for Android platform.

Create Ionic 4 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 4 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

Install & Configure Ionic 4 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.

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.

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

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.

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

Conclusion

The Ionic 4 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.

Push Notification using Ionic 4 and Firebase Cloud Messaging

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.

Table of Contents:

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

1. Setup and Configure Google Firebase Cloud Messaging

Open your browser then go to Google Firebase Console then login using your Google account.

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.

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.

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.

2. Create a new Ionic 4 App

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.

3. Add Ionic 4 Cordova Native FCM Plugin

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.

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

Add to @NgModule providers.

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

Next, open and edit src/app/app.component.ts then add this import.

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

Inject FCM and Router module to the constructor.

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 push notification from Firebase Cloud Messaging.

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

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

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

<ion-header>
&nbsp; <ion-toolbar>
&nbsp; &nbsp; <ion-title>Second</ion-title>
&nbsp; </ion-toolbar>
</ion-header>

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

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

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

this.fcm.subscribeToTopic('people');

To unsubscribe from topic, add this line.

this.fcm.unsubscribeFromTopic('marketing');

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

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](https://fcm.googleapis.com/fcm/send "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....

Next, add this JSON data to the RAW body.

{
&nbsp; "notification":{
&nbsp; &nbsp; "title":"Ionic 4 Notification",
&nbsp; &nbsp; "body":"This notification sent from POSTMAN using Firebase HTTP protocol",
&nbsp; &nbsp; "sound":"default",
&nbsp; &nbsp; "click_action":"FCM_PLUGIN_ACTIVITY",
&nbsp; &nbsp; "icon":"fcm_push_icon"
&nbsp; },
&nbsp; "data":{
&nbsp; &nbsp; "landing_page":"second",
&nbsp; &nbsp; "price":"$3,000.00"
&nbsp; },
&nbsp; &nbsp; "to":"eadego-nig0:APA91bEtKx9hv50lmQmfzl-bSDdsZyTQ4RkelInfzxrPcZjJaSgDmok3-WQKV5FBu9hrMrkRrcCmf3arkGSviGltg5CyC2F9x1J2m0W7U8PxJ3Zlh7-_tL6VcFdb76hbaLIdZ-dOK15r",
&nbsp; &nbsp; "priority":"high",
&nbsp; &nbsp; "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.

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

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

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

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.

Ionic 4 SQLite Database CRUD App Example Tutorial - positronX.io

Ionic 4 SQLite Database CRUD App Example Tutorial - positronX.io

In this tutorial, we will learn how to create Ionic 4 Angular CRUD application and implement SQLite Native plugin to store the data in the SQLite Database. We will create the Create, Read, Update and Delete operation to manage the data in the database. Moreover, we will also learn to load the dummy data from …