【问题标题】:Firebase Analytics in Xamarin FormsXamarin 表单中的 Firebase 分析
【发布时间】:2018-07-24 06:28:56
【问题描述】:

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

【问题讨论】:

    标签: firebase xamarin.forms firebase-analytics


    【解决方案1】:

    答案已针对新版本的 Xamarin Firebase 组件进行了更新并修复了各种问题

    当然,你需要DI(依赖注入)来调用平台代码。

    • 配置您的 Firebase 应用:https://firebase.google.com/docs/projects/learn-more
    • 为 Firebase Analytics 引用正确的 nuget 包:

      Android 项目

      • Xamarin.FireBase.Analytics
      • Xamarin.FireBase.Analytics.Impl
      • Plugin.CurrentActivity (用于获取当前上下文 Forms.Context 已弃用)

      iOS 项目

      • Xamarin.FireBase.iOS.Analytics(iOS 项目)
    • 在您的 PCL(或 .NETStandard)项目中创建接口

    • 在 Android 和 iOS 项目中编写平台专用代码
    • 在您的视图模型中,使用 PCL(或 .NETStandard)项目中的 DI 调用 LogEvent 方法来存储您的事件

    注意:自定义事件在 Firebase 中出现的速度很慢,根据我的经验,它们需要 24 小时才能出现在网络控制台中。如果你 想要正确测试自定义日志记录,使用您的手机并激活 分析调试(因此您可以在 debugView 中查看您的事件 firebase 控制台)*


    注意2:注意eventId 属性:名称最多可包含40 个字符,只能包含字母数字字符和 下划线 (""),并且必须以字母字符开头。这 “firebase”、“google_”和“ga_”前缀是保留的,不应 使用。我已经包含了一个小实用功能来自动修复 eventId,可以跳过


    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);
        }
    }
    

    安卓

    确保清单中有 INTERNET 权限。

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

    记得在你的AppDelegate中调用CrossCurrentActivityinit方法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 --&gt; android --&gt; android adb command prompt 中的 Visual Studio 访问它):

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

    要禁用 debugView,请使用:

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

    详细日志记录

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

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

    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 并在 teir manifest 中明确禁用分析。

    在这些情况下,您需要修改您的 AndroidManifest.xml,在 &lt;/application&gt; 标签之前添加这一行:

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

    还要确保在您的 &lt;manifest&gt; 标记中包含此属性:

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

    iOS

    请务必在您的手机上测试事件记录!这将不再适用于模拟器

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

    Firebase.Core.App.Configure();
    

    然后导入您的 GoogleService-Info.plist(从您的 firebase 帐户生成)并将编译操作设置为“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 参数中:

    --argument=-FIRDebugEnabled
    

    要禁用 debugView,请使用:

    --argument=-FIRDebugDisabled
    

    重要提示感谢Ken 指出这一点

    如果您在 AppDelegate 中调用 Firebase.Core.App.Configure(); 时遇到异常,请将您的 GoogleService-Info.plist 设置 IS_ANALYTICS_ENABLED 修改为 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");
    
        }
    }
    

    【讨论】:

    • Firebase 分析不适合 xamarin 崩溃分析。最好使用microsoft appcenter。 appcenter.ms
    • 我用它来跟踪分析数据(页面浏览量、用户参与度、自定义事件、屏幕上的时间、ecc...)。上次我检查时,appcenter 在分析部分方面落后于 Firebase。我想我需要重新检查一下!也许您在谈论 Firebase Crashlytics?这是另一个话题。 Firebase 崩溃报告已在几个月前打折并停用。
    • @GiampaoloGabba analyticsService.LogEvent("EventId","EventValue"); throwing System.NullReferenceException:“对象引用未设置为对象的实例。”错误
    • @Shanmugasundharam 示例代码错误,接口不提供 2 个字符串的重载。我已经更新了答案。还要确保向 DI 容器注册平台服务
    • @GiampaoloGabba 感谢更新,我也更新了我的代码,它运行良好,但无法从我的事件中读取数据。我猜大查询会提供原始数据。
    【解决方案2】:

    我成功地遵循了这个指南。
    不过,我有一条有用的小评论:在文件GoogleService-Info.plist 中,我必须将IS_ANALYTICS_ENABLED 设置为true。否则,我在调用Firebase.Core.App.Configure();时遇到异常

    【讨论】:

      【解决方案3】:

      您的 android 服务文件有误

      您的代码如下

      var bundle = new Bundle();
      
      foreach (var item in parameters)
      {
          bundle.PutString(FirebaseAnalytics.Param.ItemId, item.Key);
          bundle.PutString(FirebaseAnalytics.Param.ItemName, item.Value);
      }
      

      必须替换为以下以跟踪所有参数:

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

      【讨论】:

      • 谢谢。我的代码用于“建议的”firebase 事件,但甚至适用于自定义事件。但是,您的更好:) 答案已更新!
      猜你喜欢
      • 2023-01-23
      • 2020-03-26
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2018-11-25
      • 2020-05-12
      相关资源
      最近更新 更多