Categories
Frontend Development Mobile Applications Development

How to migrate Ionic 3 apps from Google Analytics to Firebase Analytics

Learn how to migrate your Ionic apps from Google Analytics to Firebase Analytics and make sure you continue tracking your app’s usage.

In case you haven’t received or read the email from Google stating that the Google Analytics for mobile apps SDKs will not continue tracking data in October 31, 2019 I want to inform you that this change from Google will force you to update your apps if you use Google Analytics for mobile apps SDKs in order to continue tracking data for your apps (Android & iOS).

This is a big change because we are used to track data for our apps with the Google Analytics for mobile SDKs, in Ionic the most common scenario for this was to use a cordova plugin like Google Analytics Cordova Plugin and the Ionic Native wrapper to access the native SDKs and track your apps’ usage data.

With this new change Google is moving the analytics tracking from the Google Analytics for mobile SDKs to its complete platform of solutions and services for mobile apps, Firebase, through the Firebase Analytics SDKs.

Luckily, for Ionic apps there is already a Firebase Analytics Cordova Plugin we can use and its relative Ionic Native wrapper that will help us move the tracking of our data from Google Analytics to Firebase.

Important Dates

  • October 31, 2019 – Data collection and processing will stop working in legacy Google Analytics for mobile apps properties.
  • January 31, 2020 – Reporting access through the web interface and APIs will stop working and legacy Google Analytics for mobile apps properties will be erased permanently from Google servers.

Requirements

  • Firebase account & Firebase project (both are free)
  • google-services.json file provided by Firebase.
  • GoogleService-Info.plist file provided by Firebase.
  • Firebase Analytics Cordova Plugin & Ionic Native wrapper.

Installation and setup

Firebase account and project setup

If you don’t have a Firebase account and project setup yet, the first thing we’ll need to do is to create a Firebase account and then create a Firebase project.

  1. Click on the Create a project button and write a name for your project.
  2. After your project is created we will need to configure the Android & iOS apps inside our new project.
  3. Click on the Gear icon next to “Project Overview”.
  4. Scroll down to the “Your apps” section.
  5. Click on the Android icon and enter your Android package name (this is normally the value of the id attribute in the widget tag of your config.xml file located in the root of your Ionic project) and then press the “register app” button.
  6. Download the google-services.json file provided by Firebase and save it in the root of your Ionic project.
  7. Ignore the step 3 and 4 in the setup of the Android app because this is more oriented to native apps.
  8. In order to configure the iOS app you’ll need to go to “Your apps” section again and click the “Add app” button.
  9. Click on the iOS icon and enter your iOS bundle ID (this is normally the value of the id attribute in the widget tag of your config.xml file located in the root of your Ionic project) and then press the “register app” button.
  10. Download the GoogleService-Info.plist file provided by Firebase and save it in the root of your Ionic project.
  11. Ignore the step 3, 4 and 5 in the setup of the iOS app because this is more oriented to native apps.
  12. By the end of this you should have the google-services.json and the GoogleService-Info.plist files next to the config.xml in your Ionic project, your root folder structure should look something like this:

Uninstall Google Analytics plugin

If you are currently tracking data with the Google Analytics Cordova Plugin you’ll need to uninstall the plugin and the Ionic native wrapper by executing the following commands in the console.

Uninstall Google Analytics Cordova Plugin:


ionic cordova plugin remove cordova-plugin-google-analytics

Uninstall Google Analytics Ionic native wrapper:


npm uninstall --save @ionic-native/google-analytics

Make sure you remove all import statements and references to this plugin in your code including the app.module.ts file.

Install Firebase Analytics plugins

Installing the Firebase Analytics SDKs in your Ionic app is a matter of running the following two commands from console.

Install Firebase Analytics Cordova Plugin:


ionic cordova plugin add cordova-plugin-firebase-analytics

If your Cordova CLI version is lower than 9.0.0 you’ll need to install version 1.1.1 of the plugin like this:


ionic cordova plugin add cordova-plugin-firebase-analytics@1.1.1

Install the Firebase Analytics Ionic native wrapper, for Ionic 3 apps you can only install version up to 4.x.x of the Ionic native wrapper like this:


npm install --save @ionic-native/firebase-analytics@4

How to track screen views?

Because Ionic apps are Single Page Applications (SPAs) running in a WebView, the concept of a screen view happens when a new Component loads and is displayed to the user on the screen.

Thanks to Lifecycle Hooks in Angular/Ionic we can hook into the moment a Component is created and loaded into the screen with the ionViewDidLoad lifecycle hook and set the screen name with the Firebase Analytics Ionic native wrapper to instruct Firebase to track the screen_view event.

A normal page for your Ionic 3 app will look something like this:


// Angular
import { Component } from '@angular/core';

// Ionic
import { IonicPage, Platform} from 'ionic-angular';
import { FirebaseAnalytics } from '@ionic-native/firebase-analytics';

@IonicPage()
@Component({
    selector: 'page-profile',
    templateUrl: 'profile.html',
})
export class ProfilePage {

    constructor(
        private platform: Platform,
        private firebaseAnalytics: FirebaseAnalytics,
    ) {

    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad ProfilePage');

        // Firebase Analytics 'screen_view' event tracking
        this.firebaseAnalytics.setCurrentScreen('Profile');
    }

}

Just by setting the current screen name the Firebase Analytics SDKs will send a screen_view event to Firebase Analytics, also all the future events tracked in this component will have the context of this screen to help identify where does the users use the app more.

IMPORTANT: When you use firebaseAnalytics.setCurrentScreen(screenName), besides from tracking a screen_view event, that screenName will be used as the firebase_screen parameter for all the future events tracked, so it’s important to always set the current screen for every component and as I mentioned above you can do this easily with the ionViewDidLoad lifecycle hook.

An option that worked well for me was to create a custom service like this:


// Angular
import { Injectable } from '@angular/core';

// Ionic
import { Platform } from 'ionic-angular';
import { FirebaseAnalytics } from '@ionic-native/firebase-analytics';

@Injectable()
export class CustomFirebaseAnalyticsProvider {

    constructor(
        private platform: Platform,
        private firebaseAnalytics: FirebaseAnalytics
    ) {
        console.log('Hello CustomFirebaseAnalyticsProvider Provider');
    }

    // Tracks an 'screen_view' event in Firebase Analytics
    trackView(screenName: string) {
        this.platform.ready().then(() => {
            this.firebaseAnalytics.setCurrentScreen(screenName);
        });
    }

    // Tracks a custom event in Firebase Analytics
    trackEvent(eventName: string, eventParams: any) {
        this.platform.ready().then(() => {
            this.firebaseAnalytics.logEvent(eventName, eventParams);
        });
    }

}

And then you can use it in your components like this:


// Angular
import { Component } from '@angular/core';

// Ionic
import { IonicPage, Platform} from 'ionic-angular';
import { CustomFirebaseAnalyticsProvider } from '../../providers/custom-firebase-analytics/custom-firebase-analytics';

@IonicPage()
@Component({
    selector: 'page-profile',
    templateUrl: 'profile.html',
})
export class ProfilePage {

    constructor(
        private platform: Platform,
        private customFirebaseAnalytics: CustomFirebaseAnalyticsProvider,
    ) {

    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad ProfilePage');

        // Firebase Analytics 'screen_view' event tracking
        this.customFirebaseAnalytics.trackView('Profile');
    }

    login() {
        let eventParams = {}
        this.customFirebaseAnalytics.trackEvent('login', eventParams);

        // Code to login users
    }

    register() {
        let eventParams = {}
        this.customFirebaseAnalytics.trackEvent('sign_up', eventParams);

        // Code to register users
    }

    logout() {
        let eventParams = {}
        this.customFirebaseAnalytics.trackEvent('logout', eventParams);

        // Code to logout users
    }

}

In this way you’ll make sure that whenever you load a Component a screen_view event will be tracked for that component and also the context of that screen will be set and used for all of the future events you’ll track in that component.

This will also help you migrate from the old Google Analytics Ionic native wrapper because with Google Analytics you use to have a googleAnalytics.trackView() method for tracking the equivalent of a screen view and you use to have a googleAnalytics.trackEvent() to track the equivalent of a custom event.

How to track custom events?

Tracking custom events is really easy with Firebase Analytics because you only need to use the firebaseAnalytics.logEvent(eventName, eventParams) method from the Ionic native wrapper.


// Angular
import { Component } from '@angular/core';

// Ionic
import { IonicPage, Platform} from 'ionic-angular';
import { FirebaseAnalytics } from '@ionic-native/firebase-analytics';

@IonicPage()
@Component({
    selector: 'page-profile',
    templateUrl: 'profile.html',
})
export class ProfilePage {

    constructor(
        private platform: Platform,
        private firebaseAnalytics: FirebaseAnalytics,
    ) {

    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad ProfilePage');

        // Firebase Analytics 'screen_view' event tracking
        this.firebaseAnalytics.setCurrentScreen('Profile');
    }

    shareContent() {
        let eventParams = {};
        this.firebaseAnalytics.logEvent('share_content', eventParams);

        // share content code
    }

    shareContentInFacebook() {
        let eventParams = {};
        this.firebaseAnalytics.logEvent('share_content_fb', eventParams);

        // share content in facebook code
    }

}

If you created a custom service like the recommendation I used at the end of the “How to track screen views” section above you can track custom events like this:


// Angular
import { Component } from '@angular/core';

// Ionic
import { IonicPage, Platform} from 'ionic-angular';
import { CustomFirebaseAnalyticsProvider } from '../../providers/custom-firebase-analytics/custom-firebase-analytics';

@IonicPage()
@Component({
    selector: 'page-profile',
    templateUrl: 'profile.html',
})
export class ProfilePage {

    constructor(
        private platform: Platform,
        private customFirebaseAnalytics: CustomFirebaseAnalyticsProvider,
    ) {

    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad ProfilePage');

        // Firebase Analytics 'screen_view' event tracking
        this.customFirebaseAnalytics.trackView('Profile');
    }

    shareContent() {
        let eventParams = {}
        this.customFirebaseAnalytics.trackEvent('share_content', eventParams);

        // share content code
    }

    shareContentInFacebook() {
        let eventParams = {}
        this.customFirebaseAnalytics.trackEvent('share_content_fb', eventParams);

        // share content in facebook code
    }

}

Debugging events in Firebase

In order to reduce battery consumption and improve performance in users apps, Firebase Analytics SDKs groups events tracked in an app and sent them in batches instead of sending every event that occurs in real time.

When debugging the events you need a way to test that you are sending the correct information to Firebase, here I share the steps you need to follow in Android and iOS to be able to receive the events in real time in the DebugView page of Firebase Analytics while you are debugging your apps.

Android debugging

  1. Connect the device to the computer via USB cable.
  2. Enable Analytics Debug mode on the Android device by executing the following command from the computer console:
    1. adb shell setprop debug.firebase.analytics.app adn.guatemala.com
  3. Make sure to disable Debug mode before building the final release to avoid issues in production apps
    1. adb shell setprop debug.firebase.analytics.app .none.

iOS debugging

  1. In Xcode select:
    1. Product > Scheme > Edit scheme
  2. Select Run from the left menu.
  3. Select the Arguments tab.
  4. In the Arguments Passed On Launch section, add:
    1. -FIRAnalyticsDebugEnabled
  5. Make sure this argument is only added for the Run Scheme to avoid issues in production apps.

If you still have some questions or you need any help please leave it in the comments or contact me in my twitter account @ yoyofercab and I’ll try to help as soon as possible. I hope this guide helps you and if you have any feedback don’t hesitate on contact me.

Resources

11 replies on “How to migrate Ionic 3 apps from Google Analytics to Firebase Analytics”

Thank you Adam, I’m still in the process of migrating historical data from Google Analytics but I wanted to make sure to keep tracking info first.

I’m not sure if you can import data from Google Analytics to Firebase directly but one thing I’ve started researching is to move data from Google Analytics to Google Big Query and I know you can sync your Firebase data to Google Big Query too, so maybe a merge of information there would be a solution, in any case if I find a better solution I’ll let you know, thanks for your comment again 👍

I am also very interested in how the transfer of historic Google Analytics data to Google Analytics for Firebase works.
The only solution seems exporting to Big Query and importing that into Firebase. Did you try this already and can you share your experience with this?

Hi Tom, thank you for your comment, I did some research and the only way you can export data directly from Google Analytics to Google Big Query is if you have Google Analytics 360, which is the paid version.

I still need to find a way to preserve historical data and I was thinking of creating a script or library to use Google Analytics Reporting API (which will be available through January 31st, 2020) to download the data and then export it to another service just to preserve this information because I don’t think you can import this data to Firebase.

In the mean time you can use the export reports feature from Google Analytics to preserve your most important data, here is the link of the export report feature: https://support.google.com/analytics/answer/1038573?hl=en

I think you might want ionViewDidEnter vs ionViewDidLoad since the latter is called **only when a view is stored in memory** not when the it becomes the active view.

Thanks for your comment Felix, that’s totally true: ionViewDidEnter will be called whenever the view becomes the active view. However, in my case, I didn’t want for the screen_view event to trigger whenever the user presses the back button and returns to a view/page that has already seen, just the first time that loads and that’s why I chose the ionViewDidLoad lifecycle hook.

Jonathan, thank you for this article.
This is great for iOS/Android. However, we deploy our app to all three platforms. As far as the PWA/Web platform, do you have any recommendations on how to handle that? I can’t seem to find any solid resources on things such as tracking page views or even a full idea on how to set that all up correctly.

Hi, thanks for this tutorial! It really helps me to migrate from Google Analytics.

Do you know how to add Crashlytics (for errors message)?

Regards!

Hi Miguel, Thank you for your comment.

I haven’t implemented Firebase Crashlytics in an app to give you an exact answer but it appears that the “Firebase” plugin in the Ionic Native docs allows you to use the crash reports functionality from Firebase.

I hope that works 😉

Leave a Reply

Your email address will not be published. Required fields are marked *