DEV Community

Victor Hugo Garcia
Victor Hugo Garcia

Posted on

Firebase Analytics in .NET MAUI

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

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

Enter fullscreen mode Exit fullscreen mode

iOS

<ItemGroup Condition="'$(TargetFramework)' == 'net7.0-ios'">
        <BundleResource Include="GoogleService-Info.plist" />
        <PackageReference Include="Xamarin.Firebase.iOS.Analytics" Version="8.10.0.1" />
</ItemGroup>
Enter fullscreen mode Exit fullscreen mode

Make sure Analytics is enabled on the .plist file you added to the project for iOS:

<key>IS_ANALYTICS_ENABLED</key>
<true></true>
Enter fullscreen mode Exit fullscreen mode

Initialize the Firebase services

In the MauiProgram.cs file, the Firebase services must be initialized.

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;
    }
Enter fullscreen mode Exit fullscreen mode

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

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.

Then apply some 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

Top comments (14)

Collapse
 
twannie83 profile image
Twan Munster • Edited

@vhugogarcia, very good step by step manual. please change:
Else @runtime GoogleService-Info.plist can not be found.

<ItemGroup Condition="'$(TargetFramework)' == 'net7.0-ios'">
<BundleResource Include="GoogleService-Info.plist" />
<PackageReference Include="Xamarin.Firebase.iOS.Analytics" Version="8.10.0.1" />
</ItemGroup>

To

<ItemGroup Condition="'$(TargetFramework)' == 'net7.0-ios'">
<BundleResource Include="GoogleService-Info.plist" Link="GoogleService-Info.plist" />
<PackageReference Include="Xamarin.Firebase.iOS.Analytics" Version="8.10.0.1" />
</ItemGroup>

Collapse
 
javvy5 profile image
Oscar Peña

Muchas gracias Victor. En estos temas de MAUI .NET la documentación es realmente escasa por lo que se valora mucho tu esfuerzo.

Collapse
 
twannie83 profile image
Twan Munster • Edited

@vhugogarcia Nice step by step! Can you please add this, piece of code to .CSPRJ to support the buildaction of GoogleService-Info.plist
<ItemGroup>
<AvailableItemName Include="GoogleServicesJson" />
</ItemGroup>

Collapse
 
vhugogarcia profile image
Victor Hugo Garcia

Hello @twcrs99 , thanks for sharing this recommendation, however, I'm unclear why do we need this for the GoogleServe.Info.plist. If you can give me a hand by sharing more details, I will be happy to update it :)

Collapse
 
mofdaddy profile image
Morten Hjort • Edited

Hi there,
I am having trouble recording screen_name as a parameter to screen_view after migrating a Xamarin.iOS app to .Net 8, using the same nugets as before migration, which are the same as in this article.

It doesn't show up under Pages title/Screen name, even after waiting a day or two. On Realtime overview the device shows up active, and custom events tracks ok, only screen name is missing.

The Android version tracks fine.

Any experience with that issue?

Collapse
 
twannie83 profile image
Twan Munster

@vhugogarcia please change this setting:
<key>IS_ANALYTICS_ENABLED</key>
<true></true>

To
<key>FIREBASE_ANALYTICS_COLLECTION_ENABLED</key>
<true></true>

First is for Google Analytics second is for Firebase Analytics

Collapse
 
dpreznik profile image
Dmitriy Reznik

Hi Victor,
Thank you for your post. I am trying to apply it to my app, but when I add Xamarin.Firebase.Core NuGet package, I get a compilation error:

Type androidx.lifecycle.DispatchQueue is defined multiple times: C:\Users\dreznik.nuget\packages\xamarin.androidx.lifecycle.common\2.6.1.2\buildTransitive\net6.0-android31.0....\jar\androidx.lifecycle.lifecycle-common.jar:androidx/lifecycle/DispatchQueue.class, obj\Debug\net7.0-android\lp\199\jl\classes.jar:androidx/lifecycle/DispatchQueue.class

Could you please help?****

Collapse
 
vhugogarcia profile image
Victor Hugo Garcia

Hello @dpreznik , This makes me think that there is a missing package with the Firebase that are required to be invoked. Please refer to this repository from our friend Tobias who documented this issue and posted a solution on this comment: github.com/TobiasBuchholz/Plugin.F...

Collapse
 
eswar_rapeti_1def36e30a10 profile image
Eswar Rapeti

Hi Victor , i am facing below issue " Firebase.Core.App.Configure();" i am getting an error in the line. please help me on this.android is working fine.
This is the error

[FBSWorkspaceScenesClient createSceneWithIdentity:parameters:transitionContext:completion:]block_invoke.187 + 102
34 FrontBoardServices 0x000000012795fb8a -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 209
35 FrontBoardServices 0x00000001279803af __92-[FBSWorkspaceScenesClient createSceneWithIdentity:parameters:transitionContext:completion:]_block_invoke + 344
36 libdispatch.dylib 0x0000000123427a3a _dispatch_client_callout + 8
37 libdispatch.dylib 0x000000012342b4bf _dispatch_block_invoke_direct + 484
38 FrontBoardServices 0x00000001279a6bb8 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK
_ + 30
39 FrontBoardServices 0x00000001279a6aae -[FBSSerialQueue targetQueue_performNextIfPossible] + 174
40 FrontBoardServices 0x00000001279a6be0 -[FBSSerialQueue _performNextFromRunLoopSource] + 19
41 CoreFoundation 0x00000001128c2fe5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION
_ + 17
42 CoreFoundation 0x00000001128c2f24 __CFRunLoopDoSource0 + 157
43 CoreFoundation 0x00000001128c2721 __CFRunLoopDoSources0 + 212
44 CoreFoundation 0x00000001128bce23 __CFRunLoopRun + 927
45 CoreFoundation 0x00000001128bc6a7 CFRunLoopRunSpecific + 560
46 GraphicsServices 0x0000000127de928a GSEventRunModal + 139
47 UIKitCore 0x000000012e893ad3 -[UIApplication _run] + 994
48 UIKitCore 0x000000012e8989ef UIApplicationMain + 123
49 libxamarin-dotnet-debug.dylib 0x000000010e17ba5a xamarin_UIApplicationMain + 58
50 libmonosgen-2.0.dylib 0x000000010ea2b5f9 do_icall + 345
51 libmonosgen-2.0.dylib 0x000000010ea2a103 do_icall_wrapper + 291
52 libmonosgen-2.0.dylib 0x000000010ea1c4ff interp_exec_method + 3295
53 libmonosgen-2.0.dylib 0x000000010ea19e53 interp_runtime_invoke + 259
54 libmonosgen-2.0.dylib 0x000000010e83edd8 mono_runtime_invoke_checked + 136
55 libmonosgen-2.0.dylib 0x000000010e846dec do_exec_main_checked + 92
56 libmonosgen-2.0.dylib 0x000000010e975e42 mono_jit_exec + 354
57 libxamarin-dotnet-debug.dylib 0x000000010e1bfe77 xamarin_main + 1927
58 NPM 0x00000001044d4204 main + 52
59 dyld 0x000000010d0c82bf start_sim + 10
60 ??? 0x0000000204b7b310 0x0 + 8669082384

Collapse
 
vhugogarcia profile image
Victor Hugo Garcia

Hello @eswar_rapeti_1def36e30a10 , I believe this issue belongs to the Xamarin iOS Binding using .NET 8, also our friend Tobias was able to manage it, so, I recommend you to migrate to his library because it is up to date and ready for .NET MAUI 8: github.com/TobiasBuchholz/Plugin.F...

Collapse
 
jsgg25 profile image
jsgg25

Thanks!!

Collapse
 
indexoutoflimit profile image
Bikash Ghosh

Do we have support for Windows as well?

Collapse
 
vhugogarcia profile image
Victor Hugo Garcia

Honestly, I'm not sure the Firebase SDKs are fully ported to .NET for Windows, if they are available, I think you can certainly follow the same steps outlined in the article and integrate it with Windows. :)

Collapse
 
luz_colvin_95775c5e9c51d3 profile image
Luz Colvin

this was very helpful victor, thanks works exactly as described.
i have to use a MAC to test because of issues with support of Firebase with XCode.