Press ESC to close

Xamarin Forms Firebase Analytics

Hello friends. In this article, we will talk about how to send events with Firebase in Xamarin Forms and how to debug these events. First, we need to open a project on a Firebase. Later, we will create 2 different applications from this project. One of them will be for iOS and the other for Android.

Make sure that the bundle id is correct while creating an application in the project. We need to download and add the files google-services.json for Android and GoogleServiceInfo.plist for iOS, which are the last step of creating an application. The point we need to pay attention here is; After adding the json file on the Android side, we need to specify that it is a GoogleServicesJson in the BuildAction section. If this option doesn’t come, VS For Mac is totally absurd. You need to edit the csproj file on the android side of the project.

When you open your csproj file with any editor, you will probably see that your google-services.json file is None. Add this itself as GoogleServicesJson and you will see that it is fixed when you run your project again.

Then, on the iOS side, we must make sure that the Google-Services-Info.plist file we added is set as BundleResource from the Build Action option.

Now we can come to the Xamarin side. We will proceed through DependencyService as we will do different operations for each platform here. If you want to know more about what DependencyService is, there is a more detailed explanation here. First of all, we design an interface for what functions we will use in this service. Since I will only log one event, this interface will do the trick. You can customize it according to your needs.

using System;
namespace XamFirebaseEvents.DependencyServices
{
    public interface IFirebaseEvents
    {
        void LogEvent(string Id, string name, string value);
    }
}

After that, I first switch to the Android side. Here we need to install packages. These packages;

  • Xamarin.FireBase.Analytics
  • Xamarin.FireBase.Analytics.Impl

After installing the packages, I create FirebaseEvents class on the Android layer and inherit from IFirebaseEvents. I can log events thanks to the packages I added later. The part you need to pay attention to here is that when it tries to get an instance from FirebaseAnalytics, it requests an activity from you. The problem will be solved if you set the MainActivity itself of the onCreate function after defining a static variable on the MainActivity.

using System;
using Android.OS;
using Firebase.Analytics;
using XamFirebaseEvents.DependencyServices;
[assembly: Xamarin.Forms.Dependency(typeof(IFirebaseEvents))]
namespace XamFirebaseEvents.Droid.DependencyServices
{
    public class FirebaseEvents : IFirebaseEvents
    {
        public void LogEvent(string Id, string name, string value)
        {
            var firebaseAnalytics = FirebaseAnalytics.GetInstance(MainActivity.activity);
            var bundle = new Bundle();
            bundle.PutString(name, value);

            firebaseAnalytics.LogEvent(Id, bundle);
        }
    }
}

The next step is the iOS part. Here again, as we did in Android, we create a new class; We ensure that this class inherits from the interface we created. After that, we need to add the Xamarin.Firebase.iOS.Analytics package.

After adding the package, we need to add these codes to the class we created.

using System;
using System.Collections.Generic;
using Firebase.Analytics;
using Foundation;
using XamFirebaseEvents.DependencyServices;
[assembly: Xamarin.Forms.Dependency(typeof(IFirebaseEvents))]
namespace XamFirebaseEvents.iOS.DependencyServices
{
    public class FirebaseEvents : IFirebaseEvents
    {
        public void LogEvent(string Id, string name, string value)
        {
            var keys = new List<NSString>()
            {
                new NSString(name)
            };
            var values = new List<NSString>()
            {
                new NSString(value)
            };
            Analytics.LogEvent(Id, NSDictionary<NSString, NSObject>.FromObjectsAndKeys(values.ToArray(), keys.ToArray(), keys.Count));
        }
    }
}

The last action will be on AppDelegate. Here it is necessary to configure Firebase.

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;

namespace XamFirebaseEvents.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the 
    // User Interface of the application, as well as listening (and optionally responding) to 
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            Firebase.Core.App.Configure();

            return base.FinishedLaunching(app, options);
        }
    }
}

The point we need to pay attention here is; The events we log are on the console the next day. You can debug while testing events. For this, it will be useful to check the next article.

You can ask the places you want to ask by sending e-mail or comment. Good work.

Comments (3)

  • Locsays:

    Monday January 17th, 2022 at 01:24 PM

    var firebaseAnalytics = FirebaseAnalytics.GetInstance(MainActivity.activity); this line required a Context so it should be
    => var firebaseAnalytics = FirebaseAnalytics.GetInstance(Forms.Context);
    And when I check the “firebaseAnalytics” it said:

    FirebaseInstanceId = Java.Lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.xxxx. Make sure to call FirebaseApp…

    Am I missing something?
    Btw amazing article!!!

    • omersezersays:

      Monday January 17th, 2022 at 01:49 PM

      Hi,

      First of all thank you for your comment. Did you add FirebaseApp.InitializeApp() to your MainActivity? If you can share your project with me on Github, i can help to you. My github username is omersezer.

      Good works.

      • Locsays:

        Tuesday January 18th, 2022 at 07:11 AM

        Thank you for your reply. My problem was that my “package_name” in the google-services.json did not match the app’s package name. Even though it also happened on the IOS side when the “BUNDLE_ID” in the GoogleService-Info.plist does not correspond with the “Bundle identifier” in Info.plist, but it worked excellent :D. You want to pay more attention when working with those files.

Leave a Reply

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