本文介绍了Xamarin表单中的Firebase Analytics的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们能否获得自定义事件,例如说在Xamarin Forms项目中使用Firebase Analytics按下了Button 1?

Can we get custom events such as say Button 1 was pressed using Firebase Analytics in a Xamarin Forms Project ?

推荐答案

当然,您需要进行DI(依赖注入)来调用平台代码.

Sure, you need to DI (dependency injection) to call the platform code.

  • Configure your Firebase App: https://firebase.google.com/docs/projects/learn-more
  • Reference the proper nuget packages for Firebase Analytics:

Android项目

  • Xamarin.FireBase.Analytics
  • Xamarin.FireBase.Analytics.Impl
  • Plugin.CurrentActivity (用于获取当前上下文,因为不赞成使用 Forms.Context )

iOS项目

  • Xamarin.FireBase.iOS.Analytics(iOS项目)
  • Xamarin.FireBase.iOS.Analytics (iOS project)

在您的PCL(或.NETStandard)项目中,创建界面

In your PCL (or .NETStandard) project create the interface



PCL或.NETStandard项目

using System.Collections.Generic;

namespace MobileApp.Services
{
    public interface IAnalyticsService
    {
        void LogEvent(string eventId);
        void LogEvent(string eventId, string paramName, string value);
        void LogEvent(string eventId, IDictionary<string, string> parameters);
    }
}

Android

导入您的google-services.json(从您的firebase帐户生成),并将编译操作设置为"GoogleServicesJson"

Import your google-services.json (generated from your firebase account) with compilation action set to "GoogleServicesJson"

记住要在AppDelegate OnCreate中调用CrossCurrentActivity初始化方法:

Remember to call CrossCurrentActivity init method in your AppDelegate OnCreate:

CrossCurrentActivity.Current.Init(this, bundle);

这是Android平台服务代码:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Android.OS;
using Firebase.Analytics;
using Plugin.CurrentActivity;
using MobileApp.Services;

namespace MobileApp.Droid.Services
{
    [assembly: Dependency (typeof(AnalyticsServiceDroid))]
    public class AnalyticsServiceDroid : IAnalyticsService
    {

        public void LogEvent(string eventId)
        {
            LogEvent(eventId, null);
        }

        public void LogEvent(string eventId, string paramName, string value)
        {
            LogEvent(eventId, new Dictionary<string, string>
            {
                {paramName, value}
            });
        }

        public void LogEvent(string eventId, IDictionary<string, string> parameters)
        {

            //utility method to fix eventId, you can skip it if you are sure to always pass valid eventIds
            eventId = FixEventId(eventId);

            var fireBaseAnalytics = FirebaseAnalytics.GetInstance(CrossCurrentActivity.Current.AppContext);

            if (parameters == null)
            {
                fireBaseAnalytics.LogEvent(eventId, null);
                return;
            }

            var bundle = new Bundle();

            foreach (var item in parameters)
            {
                bundle.PutString(item.Key, item.Value);
            }

            fireBaseAnalytics.LogEvent(eventId, bundle);
        }

        //utility method to fix eventId, you can skip it if you are sure to always pass valid eventIds
        private string FixEventId(string eventId)
        {
            if (string.IsNullOrWhiteSpace(eventId))
                return "unknown";

            //remove unwanted characters
            eventId = Regex.Replace(eventId, @"[^a-zA-Z0-9_]+", "_", RegexOptions.Compiled);

            //trim to 40 if needed
            return eventId.Substring(0, Math.Min(40, eventId.Length));
        }

    }
}

在Android中调试视图

要在firebase中启用debugView,请从adb控制台命令提示符处运行此命令(通常为c:\WINDOWS\System32,但可以通过tools --> android --> android adb command prompt中的Visual Studio来访问它):

To enable the debugView in the firebase run this command from your adb console command prompt (usually is c:\WINDOWS\System32, but you can reach it through Visual Studio in tools --> android --> android adb command prompt):

adb shell setprop debug.firebase.analytics.app <package_name>

要禁用debugView,请使用:

To disable the debugView use:

adb shell setprop debug.firebase.analytics.app .none.

详细记录

详细日志记录是usefyk,用于监视SDK记录的事件,以帮助验证是否正确记录了事件.这包括自动和手动记录的事件.

Verbose logging is usefyk to monitor logging of events by the SDK to help verify that events are being logged properly. This includes both automatically and manually logged events.

您可以使用一系列adb命令启用详细日志记录:

You can enable verbose logging with a series of adb commands:

adb shell setprop log.tag.FA VERBOSE
adb shell setprop log.tag.FA-SVC VERBOSE
adb logcat -v time -s FA FA-SVC

一些外部库(例如MS AppCenter)已经包含Firebase,并在清单中明确禁用了分析功能.

Some external libraries (Like MS AppCenter) are already including Firebase and explicitly disabling analytics in teir manifest.

在这些情况下,您需要修改AndroidManifest.xml并在</application>标记之前添加以下行:

In these cases you need to modify your AndroidManifest.xml adding this line just before the </application> tag:

<meta-data android:name="firebase_analytics_collection_deactivated" android:value="false" tools:replace="android:value"/>

还要确保在<manifest>标记中包含此属性:

Also make sure to have this property inside your <manifest> tag:

xmlns:tools="http://schemas.android.com/tools"

iOS

在base.FinishedLaunching之前,初始化AppDelegate中的组件:

Initialize the component in your AppDelegate, just before base.FinishedLaunching:

Firebase.Core.App.Configure();

然后导入您的GoogleService-Info.plist(从您的firebase帐户生成),并将编译操作设置为"BundleResource".

Then import your GoogleService-Info.plist (generated from your firebase account) with compilation action set to "BundleResource" .

这是iOS平台服务代码:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Firebase.Analytics;
using Firebase.Core;
using Foundation;
using MobileApp.Services;

namespace MobileApp.iOS.Services
{
    [assembly: Dependency (typeof(AnalyticsServiceIOS))]
    public class AnalyticsServiceIOS : IAnalyticsService
    {

        public void LogEvent(string eventId)
        {
            LogEvent(eventId, (IDictionary<string, string>)null);
        }

        public void LogEvent(string eventId, string paramName, string value)
        {
            LogEvent(eventId, new Dictionary<string, string>
            {
                { paramName, value }
            });
        }

        public void LogEvent(string eventId, IDictionary<string, string> parameters)
        {

            //utility method to fix eventId, you can skip it if you are sure to always pass valid eventIds
            eventId = FixEventId(eventId);

            if (parameters == null)
            {
                Analytics.LogEvent(eventId, parameters: null);
                return;
            }

            var keys = new List<NSString>();
            var values = new List<NSString>();
            foreach (var item in parameters)
            {
                keys.Add(new NSString(item.Key));
                values.Add(new NSString(item.Value));
            }

            var parametersDictionary =
                NSDictionary<NSString, NSObject>.FromObjectsAndKeys(values.ToArray(), keys.ToArray(), keys.Count);
            Analytics.LogEvent(eventId, parametersDictionary);

        }

        //utility method to fix eventId, you can skip it if you are sure to always pass valid eventIds
        private string FixEventId(string eventId)
        {
            if (string.IsNullOrWhiteSpace(eventId))
                return "unknown";

            //remove unwanted characters
            eventId = Regex.Replace(eventId, @"[^a-zA-Z0-9_]+", "_", RegexOptions.Compiled);

            //trim to 40 if needed
            return eventId.Substring(0, Math.Min(40, eventId.Length));
        }
    }
}

在iOS中调试视图

要在firebase控制台中启用debugView,请在iOS项目属性中的Extra mlaunch 参数中添加以下参数:

To enable the debugView in the firebase console add the following argument to Extra mlaunch Arguments in your iOS project properties:

--argument=-FIRDebugEnabled

要禁用debugView,请使用:

To disable the debugView use:

--argument=-FIRDebugDisabled

如果在AppDelegate中遇到调用Firebase.Core.App.Configure();的异常,请将GoogleService-Info.plist设置IS_ANALYTICS_ENABLED修改为true

If you get an exception calling Firebase.Core.App.Configure(); in your AppDelegate, modify your GoogleService-Info.plist settings IS_ANALYTICS_ENABLED to true

在ViewModel中,您可以跟踪所需的任何事件

例如:

public class MenuPageViewModel{
    public MenuPageViewModel(){
         var analyticsService= DependencyService.Get<IAnalyticsService>();
         //You can use any of the LogEvent Overloads, for example:
         analyticsService.LogEvent("Event");

    }
}

这篇关于Xamarin表单中的Firebase Analytics的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 14:30