Firebase Crashlytics in .NET MAUI
Tags: dotnet, dotnetmaui, maui, firebase
Published: 2022-11-15 13:30:10

**Firebase** is an app development platform that helps you build and grow apps. Firebase Crashlytics is an error reporting solution available at no charge. In this post, I’ll show you how to implement Firebase Crashlytics 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 Crashlytics 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.Crashlytics" Version="118.2.13" />
</ItemGroup>
	
```

> Create a _strings.xml_ file under the following folder: _Platforms/Android/Resources/values_ and set the following content
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="google_app_id"><!-- YOUR APP ID FROM FIREBASE --></string>
	<string name="com.crashlytics.android.build_id">2.0</string>
</resources>
```

**iOS**

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

## 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();
Firebase.Crashlytics.Crashlytics.SharedInstance.Init();
Firebase.Crashlytics.Crashlytics.SharedInstance.SetCrashlyticsCollectionEnabled(true);
Firebase.Crashlytics.Crashlytics.SharedInstance.SendUnsentReports();
                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 Crashlytics should be identified by the Firebase console and waiting for the first crash.

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

## Log non-fatal exceptions
We all have at least one try and catch in our app somewhere, or maybe a custom validation you would like to log and track into Crashlytics that may be important for your app to function properly. 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/ae60e3a1f902da1e285d5b54fde2acb5 %}

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:
```csharp
try
{
    // Sample code goes here
}
catch(Exception ex)
{
    Debug.WriteLine(ex.ToString());
    _firebaseCrashlyticsService.Log(ex);
}
```

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