Xamarin.Forms - Working With Firebase Analytics

In this article, you will learn how to implement Firebase Analytics in Xamarin.Forms mobile app.

Introduction

 
Xamarin.Forms - Working With Firebase Analytics
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
 

Firebase

 
Firebase gives you functionality like analytics, databases, messaging, and crash reporting so you can move quickly and focus on your users.
 
Xamarin.Forms - Working With Firebase Analytics
 
Firebase is a back-end platform for building Web, Android, and iOS applications. It offers a real-time database, different APIs, multiple authentication types and hosting platforms. This is an introductory tutorial, which covers the basics of the Firebase platform and explains how to deal with its various components and sub-components.
 

Build apps with Firebase

  1. Real-time Database
  2. Storage
  3. Notifications
  4. Authentication
  5. Hosting

Firebase Analytics

 
Google Analytics for Firebase provides free, unlimited reporting on up to 500 distinct events. The SDK automatically captures certain key events and user properties, and you can define your own custom events to measure the things that uniquely matter to your business.
 
For more
 
https://firebase.google.com/docs/analytics
 
Xamarin.Forms - Working With Firebase Analytics 
 
Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
  • Firebase Account

Setting up a Xamarin.Forms Project

 
https://github.com/susairajs/XamarinForms_FirebaseAnalytics
 
Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.
 
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.
 
Now, you need to click "Create a new project".
 
Xamarin.Forms - Working With Firebase Analytics
 
Now, filter by Project Type: Mobile
 
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the Play button to try it out.
 

Setting up the User Interface

 
Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="XMonkey.Views.FeedPage">    
  3.     <ContentPage.Content>    
  4.             
  5.         <FlexLayout Direction="Column"    
  6.                 AlignItems="Center">    
  7.                 <Image Source="banner.png"/>    
  8.                 <Image Source="firebase.png" WidthRequest="200"/>    
  9.         <Button Margin="0,50,0,0" Text="Click Me" Clicked="Handle_Clicked" />    
  10.     
  11.     </FlexLayout>    
  12.     </ContentPage.Content>    
  13. </ContentPage>    
NuGet Package
 
Now, add the following NuGet package in your .Net Standard Project.
  • Xamarin.Firebase.Core

Create an Interface IFirebaseAnalytics

 
Now, create an interface in .NET Standard Project.
 
Write the following code.
 
IFirebaseAnalytics.cs
  1. public interface IFirebaseAnalytics  
  2.     {  
  3.         void SendEvent(string eventId);  
  4.         void SendEvent(string eventId, string paramName, string value);  
  5.         void SendEvent(string eventId, IDictionary<stringstring> parameters);  
  6.     }  

Android Implementation

 
Create a project in Firebase
 
In this step, create a project in Firebase. Go to the following link.
https://console.firebase.google.com/
 
Click "Add Project".
 
Now, give the project a name and select your country. Then, read the terms. Afterward, click "Create project".
 
Now, your project is ready, click "Continue".
 
Xamarin.Forms - Working With Firebase Analytics
 
Add Firebase to your Android App
 
Xamarin.Forms - Working With Firebase Analytics 
 
Register your Android app in Firebase with Android package name, app name(optional), and your debuting signing certificate(optional) then click on "Register app".
 
Xamarin.Forms - Working With Firebase Analytics
 
Done! Now, you will get one google-service.json file; you should download it.
 
Xamarin.Forms - Working With Firebase Analytics
 
Add google-service.json in your ProjectName.Android project and set Bundle Action GoogleServicesJson.
 
Add following ItemGroup in your ProjectName.Android.csproj file.
  1. <ItemGroup>    
  2.   <GoogleServicesJson Include="google-services.json" />    
  3. </ItemGroup>   
NuGet Package
 
Now, add the following NuGet package in your Android project.
  • Xamarin.FireBase.Analytics.Impl
Create class FirebaseAnalytics in Android project.
 
FirebaseAnalytics.cs
  1. [assembly: Xamarin.Forms.Dependency(typeof(FirebaseAnalytics))]  
  2. namespace XMonkey.Droid  
  3. {  
  4.     public class FirebaseAnalytics:IFirebaseAnalytics  
  5.     {  
  6.         public void SendEvent(string eventId)  
  7.         {  
  8.             SendEvent(eventId, null);  
  9.         }  
  10.   
  11.         public void SendEvent(string eventId, string paramName, string value)  
  12.         {  
  13.             SendEvent(eventId, new Dictionary<stringstring>  
  14.             {  
  15.                 {paramName, value}  
  16.             }); ;  
  17.         }  
  18.   
  19.         public void SendEvent(string eventId, IDictionary<stringstring> parameters)  
  20.         {  
  21.             var firebaseAnalytics = FirebaseAnalytics.GetInstance(Forms.Context);  
  22.   
  23.             if (parameters == null)  
  24.             {  
  25.                 firebaseAnalytics.LogEvent(eventId, null);  
  26.                 return;  
  27.             }  
  28.   
  29.             var bundle = new Bundle();  
  30.             foreach (var param in parameters)  
  31.             {  
  32.                 bundle.PutString(param.Key, param.Value);  
  33.             }  
  34.   
  35.             firebaseAnalytics.LogEvent(eventId, bundle);  
  36.         }  
  37.     }  

iOS Implementation


Add Firebase to your iOS App
 
Register your iOS app in Firebase with iOS Bundle id, app nickname(optional), and App Store id(optional) then click on "Register app".
 
Xamarin.Forms - Working With Firebase Analytics 
 
You will get one GoogleService-Info.plist file; you should download it. 
Xamarin.Forms - Working With Firebase Analytics 
 
Now, add GoogleService-Info.plist in your ProjectName.iOS project and set Bundle Action Bundle Resource.
 
NuGet Package
 
Now, add the following NuGet package in your iOS project.
  • Xamarin.FireBase.iOS.Analytics
Create class FirebaseAnalytics in the iOS project.
 
FirebaseAnalytics.cs
  1. [assembly: Dependency(typeof(FirebaseAnalytics))]  
  2. namespace XMonkey.iOS  
  3. {  
  4.     public class FirebaseAnalytics: IFirebaseAnalytics  
  5.     {  
  6.         public void SendEvent(string eventId)  
  7.         {  
  8.             SendEvent(eventId, (IDictionary<stringstring>)null);  
  9.         }  
  10.   
  11.         public void SendEvent(string eventId, string paramName, string value)  
  12.         {  
  13.             SendEvent(eventId, new Dictionary<stringstring>  
  14.             {  
  15.                 { paramName, value }  
  16.             });  
  17.         }  
  18.   
  19.         public void SendEvent(string eventId, IDictionary<stringstring> parameters)  
  20.         {  
  21.             if (parameters == null)  
  22.             {  
  23.                 Analytics.LogEvent(eventId, (Dictionary<objectobject>)null);  
  24.                 return;  
  25.             }  
  26.   
  27.             var keys = new List<NSString>();  
  28.             var values = new List<NSString>();  
  29.             foreach (var item in parameters)  
  30.             {  
  31.                 keys.Add(new NSString(item.Key));  
  32.                 values.Add(new NSString(item.Value));  
  33.             }  
  34.   
  35.             var parametersDictionary =  
  36.                 NSDictionary<NSString, NSObject>.FromObjectsAndKeys(values.ToArray(), keys.ToArray(), keys.Count);  
  37.             Analytics.LogEvent(eventId, parametersDictionary);  
  38.         }  
  39.     }  
  40. }  
Note
Go to Run -> Run With -> Custom Configuration and add the following to Extra mlaunch Arguments:
  1. --argument=-FIRAnalyticsDebugEnaled  
Finally, add the Click Event in MainPage.xaml.cs.
  1. public partial class FeedPage : ContentPage  
  2.     {  
  3.         IFirebaseAnalytics eventTracker;  
  4.         public FeedPage()  
  5.         {  
  6.             InitializeComponent();  
  7.             eventTracker = DependencyService.Get<IFirebaseAnalytics>();    
  8.         }  
  9.   
  10.   
  11.         void Handle_Clicked(object sender, System.EventArgs e)  
  12.         {  
  13.             eventTracker.SendEvent("Click1");  
  14.         }  
  15.     }  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working With Firebase Analytics
 
Check your app analytics in Firebase
 
Xamarin.Forms - Working With Firebase Analytics
 
Xamarin.Forms - Working With Firebase Analytics 
 
Xamarin.Forms - Working With Firebase Analytics
 
Download Full Project From GitHub
 
https://github.com/susairajs/XamarinForms_FirebaseAnalytics
 
I hope you have understood how to implement Firebase Analytics in Xamarin.Forms mobile app.
 
Thanks for reading. Please share your comments and feedback. Happy Coding :)