Firebase Analytics in .NET MAUI
Tags: dotnet, dotnetmaui, maui, firebase
Published: 2022-10-31 14:09:18

**Firebase** is an app development platform that helps you build and grow apps. At the heart of Firebase is Google Analytics, an unlimited analytics solution available at no charge. Analytics integrates across Firebase features and provides you with unlimited reporting for up to 500 distinct events that you can define using the Firebase SDK. In this post, I’ll show you how to implement Firebase Analytics in your **.NET MAUI** app.

---

## Setup a Firebase project

- Create a Firebase project in the [Firebase Console](https://console.firebase.google.com/), if you don't already have one by clicking _Add Project_ button.

- Make sure you enabled Google Analytics in your project.

- Add **GoogleService-Info.plist** for iOS and **google-services.json** for Android files to your app project at the root level.

- Right-click the **GoogleService-Info.plist** file and set the build action to Bundle Resource, then right-click the **google-services.json** and set build action to GoogleServicesJson.

## Required packages and project conditions
- Add the NuGet packages required to enable Firebase Analytics on iOS and Android or edit the _.csproj_ file and set them up there:

**Android**
```xml
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0-android'">
	  <GoogleServicesJson Include="google-services.json" />
	  <PackageReference Include="Xamarin.Firebase.Core" Version="121.1.1" />
	  <PackageReference Include="Xamarin.Firebase.Analytics" Version="121.1.1" />
</ItemGroup>
	
```

**iOS**

```xml
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0-ios'">
		<BundleResource Include="GoogleService-Info.plist" />
        <PackageReference Include="Xamarin.Firebase.iOS.Analytics" Version="8.10.0.1" />
</ItemGroup>
```
Make sure Analytics is enabled on the .plist file you added to the project for iOS: 

```xml
<key>IS_ANALYTICS_ENABLED</key>
<true></true>
```
## Initialize the Firebase services
In the _MauiProgram.cs_ file, the Firebase services must be initialized.

```csharp
private static MauiAppBuilder RegisterFirebase(this MauiAppBuilder builder)
    {
        builder.ConfigureLifecycleEvents(events =>
        {
#if IOS
            events.AddiOS(iOS => iOS.FinishedLaunching((app, launchOptions) => {
                Firebase.Core.App.Configure();
                return false;
            }));
#else
            events.AddAndroid(android => android.OnCreate((activity, bundle) => {
                Firebase.FirebaseApp.InitializeApp(activity);
            }));
#endif
        });

        return builder;
    }
```

Then on the static CreateMauiApp method register the Firebase Services:
`builder.RegisterFirebase();`

## Rebuild and Run
Up to this point, Firebase Analytics should start showing data on the real-time page. You can run the app on Android emulators or iOS simulators and the data should appear in the Firebase console as you can see it on the image below after 2 to 3 minutes of running the app:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ok80pfns70tjb7zs97kk.png)

## Logging
Well, we learned how to set up firebase analytics on the mobile app, however, you may want to log custom events and screen views, and this is certainly possible. Please find below how I integrated this by using platform-specific API.

**Why platform-specific API?**

Well, I found this way easier to maintain and update over time. If you want to support macOS and/or Windows, well the code below is ready for you to add the supported platform API for logging custom events.

{% embed https://gist.github.com/vhugogarcia/abbdafa01d17c754eab747e06d2c7653 %}

Then apply some [Dependency Injection](https://learn.microsoft.com/en-us/dotnet/architecture/maui/dependency-injection) for registering the services in the MauiProgram.cs file and log a custom event from any ViewModel or View:
`_firebaseAnalyticsServices.Log("MainPage");`

Thanks for reading! Follow me on Twitter **[@ivictorhugo](https://twitter.com/ivictorhugo)**