enappd loader


How to use Firebase in your Ionic 4 app — Guide for beginners



TaaDaaa, you are in luck today. Check it out below & help us in spreading the goodness all over !!
Firebase Starter Kit (Ionic 4)A great starter to get you started with Ionic 4 and Firebase.

Now lets take a dive to know the paramount benefits of Firebase for your Ionic4 App.

Firebase is a mobile and web application development platform developed by Firebase Inc. in 2011, then was acquired by Google in 2014. Firebase is a toolset to “build, improve, and grow your app”. It gives you functionality like analytics, databases, messaging and crash reporting so you can move quickly and focus on your users.

Today Firebase is one of the fastest growing platform for application development. Some of the reason are

  1. You don’t need to write a back-end from scratch. Firebase is a ready-made back-end, with a DB attached to it. You just integrate Firebase SDK in your app and you are good to go.
  2. It’s R-E-A-L T-I-M-E 🕺.
    If you are a developer, you understand the importance of a real-time back-end/database in today’s app market. Things like chat, news feeds, ratings, bookings etc all are very easy if you factor in real-time operations
  3. Simple Authentication operations.
    The very first things required in a user facing application is login/register operations. Firebase handles this very smoothly and with minimum coding effort. You can integrate a number of social authentication services like Facebook, Google etc. with Firebase as well.
  4. You get tonnes of additional features in-built e.g. push notifications, analytics etc 😍😍
  5. It’s free, up to a certain usage limit. But this is pretty awesome for developers who are trying things, or making MVPs, or even for small scale app businesses. 🤑

In this article, we will focus on what you can do with Firebase in your Ionic 4 app. Firebase has been around since Ionic 1, and has been changing ever since. So here are some of the latest plugins and functionalities you can implement using Firebase with Ionic 4

1. Analytics Firebase



Everybody knows about Google Analytics. Analytics comes in-built with Firebase. It’s a free and unlimited analytics solution. Analytics helps you understand how your users behave, so you can make informed decisions about how to market your app. Also to see the performance of your campaigns across organic and paid channels to understand which methods are most effective at driving high-value users.

Install the plugin with

ionic cordova plugin add cordova-plugin-firebase-analytics
npm install @ionic-native/firebase-analytics

For all plugins, the step to import the plugin in a component will remain common (just change the plugin name)

import { FirebaseAnalytics } from '@ionic-native/firebase-analytics/ngx';

constructor(private firebaseAnalytics: FirebaseAnalytics) {  
... your code here
}

From setup, it’ll automatically begin tracking a defined set of events — meaning we can begin learning from the very first step. And if that isn’t enough, then we can add our own custom events that we can track by

this.firebaseAnalytics.logEvent('my_event', {param1: "value1"})
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));


This is how Firebase automatically projects the analytics for your app

Following is a list of useful Firebase functions that you can write in a similar fashion as above

  1. Set User Id — this.firebaseAnalytics.setUserId("123123") 
    This is useful to identify events with respect to users.
  2. Set User Property — this.firebaseAnalytics.setUserProperty("name","value") 
    This is useful to create filters with respect to users doing a certain action or behaving a certain way to an event in the app. These filters come in handy when you want to send push notification or in-app messages to selected channels.
  3. Set Current Screen — this.firebaseAnalytics.setUserId("123123") 
    This option comes in handy to identify events with respect to screens. For example — which screen do users usually quit the app on etc.

All of these events are then viewable through the Firebase Dashboard within the Firebase Console — our central point of access for analytics reports and other firebase services.



Firebase Dashboard for Events Analytics

Note: This plugin depends on cordova-support-google-services for setting up google services properly. You can refer the README carefully in order to avoid common issues with a project configuration. Also, use variable FIREBASE_CORE_VERSION to override dependency version on Android.

On iOS, in order to collect demographic, age, gender data etc. you should additionally include AdSupport.frameworkinto your project.

2. Firebase Cloud Messaging (FCM)



Imagine a Whatsapp where you have to open the app each time to check for new messages, terrible right? Push notification is one of the best proven method to engage your app users.
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. If your app is going to be a success, then you need to hold the user’s interest over time, and notifications are an important way to keep your audience engaged. By presenting the user with a timely, relevant notification at exactly the right moment, you can recapture their wandering interest, and pull them back into your app.

Install the plugin with

ionic cordova plugin add cordova-plugin-firebase-analytics
npm install @ionic-native/firebase-analytics

Import the plugin in your root component.

import { FCM } from '@ionic-native/fcm/ngx';
constructor(private fcm: FCM) {}

Use following functions to make the best use of push notifications

I. Receiving Token Refresh

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

Note that this callback will be fired every time a new token is generated, including the first time.

II. Get token

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

Keep in mind this function will return null if the token has not been established yet. So do not call this function before the plugin is properly initialized.

III. Subscribe to topic

this.fcm.subscribeToTopic('marketing');

Topics are specific channels to provide filtered data to a specific set of users. E.g. If you are a food delivery app, you may want to send coupons to only those users who haven’t ordered anything in last 7 days.
All devices are subscribed automatically to ‘all’ and ‘ios’ or ‘android’ topic respectively, depending on the device type. If you are making a custom topic, your topic name must match the following regular expression:
“[a-zA-Z0–9-_.~%]{1,900}”

IV. Unsubscribe from topic

this.fcm.unsubscribeFromTopic('marketing');

This function is specially useful when a user wants to turn off push notifications in the app.

V. Receiving push notification data

this.fcm.onNotification().subscribe(data => {
if(data.wasTapped){
console.log("Push received in background");
} else {
console.log("Push received in foreground");
};
});

Important thing to understand here is the types of payloads. There are two types — Data and Notification. Firebase admin panel allows you to send payloads very easily and provides various options to filter as well



Prepare a Push notification right from Firebase console

You can also send payloads from your server, using FCM. The syntax for the payload will be

{
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"data":{
"param1":"value1",
"param2":"value2"
},
"to":"/topics/topicExample",
"priority":"high",
"restricted_package_name":""
}

Full documentation for sending notification via your server can be found here

3. Firebase (Remote) Config



Firebase Remote Config is a cloud service that lets you change the behavior and appearance of your app without requiring users to download an app update. When using Remote Config, you create in-app default values that control the behavior and appearance of your app. Then, you can later use the Firebase console or the Remote Config REST API to override in-app default values for all app users or for segments of your user base. For example, you can change your app’s layout or color theme to support a seasonal promotion, with no need to publish an app update.

Install the plugin with

ionic cordova plugin add cordova-plugin-firebase-config
npm install @ionic-native/firebase-config

Import the plugin in your component.

import { FirebaseConfig } from '@ionic-native/firebase-config/ngx';
constructor(private firebaseConfig: FirebaseConfig) { }

You can then get server side parameters which can tell your app how to behave specifically. Also, Firebase console allows you to add the params in a simple GUI.

this.firebaseConfig.getBoolean('is_my_holiday_promotion_on')
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));


Define Remote config parameters in Firebase console

A hidden, but great feature of Remote config is segmentation of users who receive the custom param. E.g. You want to send a particular promo code to users only from India. You can then set your holiday_promo_code param with condition set to user country : India in Firebase console



Setting custom conditions for Firebase Remote Config

4. Firebase dynamic links



Dynamic Links are smart URLs that allow you to send existing and potential users to any location within your iOS or Android app. Dynamic Links solve the problems faced in Deeplinks, where things were not as streamlined. If a user didn’t have your app installed, that deeplink wouldn’t work. Or, if a user installs your app from a deeplink, the information associated with the deeplink itself (e.g. a coupon code) gets lost in the installation process.

Dynamic Links survive the app install process, so even new users see the content they’re looking for when they open the app for the first time. If a user opens the same dynamic links in a desktop browser, they will be taken to the equivalent content on your website.



Add Dynamic Links from Firebase Console

With dynamic links, your users get the best available experience for the platform they open your link on. Key benefits of dynamic links:

  • Convert mobile web users to native app users. Send users to app store or show them an advertisement
  • Increase conversion for user-to-user sharing. e.g. app invites , coupons etc.
  • Drive more installs with social, email, and SMS marketing campaigns.
  • Turn desktop users into mobile app users. Send users to app store
  • User specific conversion — If a user installed your Food app from an ad that mentioned Chinese Food, then after installation, you can take the user directly to a Chinese restaurant page. Cool, right ?

Install the plugin with

ionic cordova plugin add cordova-plugin-firebase-dynamiclinks
npm install @ionic-native/firebase-dynamic-links

Import the plugin in your component.

import { FirebaseDynamicLinks } from '@ionic-native/firebase-dynamic-links/ngx';

constructor(private firebaseDynamicLinks: FirebaseDynamicLinks) { }

Handle the logic here after opening the app with the Dynamic link

this.firebaseDynamicLinks.onDynamicLink()
.subscribe((res: any) => console.log(res), (error:any) => console.log(error));

Use variable APP_DOMAIN to specify web URL where your app will start an activity to handle the link.

Use variable PAGE_LINK_DOMAIN to specify your *.page.link domain.

Use variable FIREBASE_DYNAMIC_LINKS_VERSION to override dependency version on Android.

5. Firebase Authentication

Use our Firebase Starter Kit to get started with Firebase Authentication.



Most apps need to know the identity of a user. Knowing a user’s identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user’s devices. Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.



Firebase provides various methods to authenticate users

Install the plugin with

ionic cordova plugin add cordova-plugin-firebase-authentication
npm install @ionic-native/firebase-authentication

Import the plugin in your component.

import { FirebaseAuthentication } from '@ionic-native/firebase-authentication/ngx';
constructor(private firebaseAuthentication: FirebaseAuthentication) { }

You can use following functions to do various tasks in authentication modules.

I. Register a User with Email and Password

this.firebaseAuthentication.createUserWithEmailAndPassword('test@gmail.com', '123')
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

II. Send Email Verification

Initiates email verification for the current user.

this.firebaseAuthentication.sendEmailVerification()
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

III. Send Password Reset Email

Triggers the Firebase Authentication backend to send a password-reset email to the given email address, which must correspond to an existing user of your app.

this.firebaseAuthentication.sendPasswordResetEmail()
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

IV. Login with Email & Password

Asynchronously signs in using an email and password.

this.firebaseAuthentication.signInWithEmailAndPassword('test@gmail.com', '123')
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

V. verifyPhoneNumber(phoneNumber, timeout)

Starts the phone number verification process for the given phone number.

this.firebaseAuthentication.verifyPhoneNumber('+123456789', '30000')
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

VI. Sign-in anonymously

Create and use temporary anonymous account to authenticate with Firebase.

this.firebaseAuthentication.signInAnonymously().then(function(userInfo) {
// user is signed in
});

VII. Google login — signInWithGoogle(idToken, accessToken)

Uses Google’s idToken and accessToken to sign-in into firebase account. In order to retrieve those tokens follow instructions for Android and iOS.

VIII. Facebook login — signInWithFacebook(accessToken)

Uses Facebook’s accessToken to sign-in into firebase account. In order to retrieve those tokens follow instructions for Android and iOS.

IX. Twitter login — signInWithTwitter(token, secret)

Uses Twitter’s token and secret to sign-in into firebase account. In order to retrieve those tokens follow instructions for Android and iOS.

X. Sign out

Signs out the current user and clears it from the disk cache.

this.firebaseAuthentication.signOut().then(function() {
// user was signed out
});

Conclusion:

In this blog we learnt about a lot of features provided by Firebase for Ionic apps. You can create user auth modules to analytics, dynamic link for invites, push notifications, remote config and much more. Firebase is truly a great match for modern day mobile apps and is really developer friendly.


An opportunity to be an ANGEL is right over here!!
Don’t forget to share word about the Firebase Starter Kit (Ionic 4)Give a boost to fellow budding Ionic app makers.





Title
Subtitle
Kicker