Xamarin 表单中的 Firebase 分析 [英] Firebase Analytics in Xamarin Forms
问题描述
我们能否获得自定义事件,例如在 Xamarin Forms 项目中使用 Firebase Analytics 按下按钮 1?
针对新版本的 Xamarin Firebase 组件更新了答案并修复了各种问题
当然,你需要DI(依赖注入)来调用平台代码.
- 配置您的 Firebase 应用:https://firebase.google.com/docs/projects/了解更多
为 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 小时才能出现在 web 控制台中.如果你想要正确测试自定义日志记录,使用您的手机并激活分析调试(因此您可以在 debugView 中查看您的事件Firebase 控制台)*
<小时><块引用>
注意 2: 注意 eventId
属性:名称最长可达 40 个字符,只能包含字母数字字符和下划线 (""),并且必须以字母字符开头.这firebase"、google_"和ga_"前缀是保留的,不应使用.我已经包含了一个小的实用程序功能来自动修复eventId,你可以跳过它
<小时>
PCL 或 .NETStandard 项目
使用 System.Collections.Generic;命名空间 MobileApp.Services{公共接口 IAnalyticsService{void LogEvent(string eventId);void LogEvent(string eventId, string paramName, string value);void LogEvent(string eventId, IDictionary parameters);}}
安卓
<块引用>确保在您的清单中具有 INTERNET 权限.
导入您的 google-services.json(从您的 firebase 帐户生成),并将编译操作设置为GoogleServicesJson"
记得在你的 AppDelegate OnCreate
中调用 CrossCurrentActivity
init 方法:
CrossCurrentActivity.Current.Init(this, bundle);
这是Android平台服务代码:
使用系统;使用 System.Collections.Generic;使用 System.Text.RegularExpressions;使用Android.OS;使用 Firebase.Analytics;使用 Plugin.CurrentActivity;使用 MobileApp.Services;命名空间 MobileApp.Droid.Services{[组装:依赖(typeof(AnalyticsServiceDroid))]公共类 AnalyticsServiceDroid : IAnalyticsService{public void LogEvent(string eventId){LogEvent(eventId, null);}public void LogEvent(string eventId, string paramName, string value){LogEvent(eventId, new Dictionary;{{参数名称,值}});}public void LogEvent(string eventId, IDictionary parameters){//修复eventId的实用方法,如果你确定总是传递有效的eventIds,你可以跳过它eventId = FixEventId(eventId);var fireBaseAnalytics = FirebaseAnalytics.GetInstance(CrossCurrentActivity.Current.AppContext);如果(参数==空){fireBaseAnalytics.LogEvent(eventId, null);返回;}var bundle = new Bundle();foreach(参数中的var item){bundle.PutString(item.Key, item.Value);}fireBaseAnalytics.LogEvent(eventId, bundle);}//修复eventId的实用方法,如果你确定总是传递有效的eventIds,你可以跳过它私有字符串 FixEventId(字符串 eventId){if (string.IsNullOrWhiteSpace(eventId))返回未知";//删除不需要的字符eventId = Regex.Replace(eventId, @"[^a-zA-Z0-9_]+", "_", RegexOptions.Compiled);//如果需要,修剪到40return eventId.Substring(0, Math.Min(40, eventId.Length));}}}
Android 中的调试视图
要在 firebase 中启用 debugView,请从 adb 控制台命令提示符运行此命令(通常是 c:WINDOWSSystem32
,但您可以通过 tools 中的 Visual Studio 访问它 --> android --> android adb 命令提示符
):
adb shell setprop debug.firebase.analytics.app
要禁用 debugView 使用:
adb shell setprop debug.firebase.analytics.app .none.
详细日志
详细日志记录用于监视 SDK 的事件日志记录,以帮助验证事件是否被正确记录.这包括自动和手动记录的事件.
您可以使用一系列 adb 命令启用详细日志记录:
adb shell setprop log.tag.FA VERBOSEadb shell setprop log.tag.FA-SVC VERBOSEadb logcat -v 时间 -s FA FA-SVC
<块引用>
重要提示
一些外部库(如 MS AppCenter)已经包含 Firebase 并在 teir manifest 中明确禁用分析.
在这些情况下,您需要修改 AndroidManifest.xml
在 </application>
标记之前添加以下行:
<meta-data android:name="firebase_analytics_collection_deactivated" android:value="false" tools:replace="android:value"/>
还要确保在你的
标签中有这个属性:
xmlns:tools="http://schemas.android.com/tools"
iOS
<块引用>请务必在手机上测试事件记录!这将不再适用于模拟器
在你的 AppDelegate 中初始化组件,就在 base.FinishedLaunching 之前:
Firebase.Core.App.Configure();
然后导入您的 GoogleService-Info.plist(从您的 firebase 帐户生成),并将编译操作设置为BundleResource".
这是iOS平台服务代码:
使用系统;使用 System.Collections.Generic;使用 System.Text.RegularExpressions;使用 Firebase.Analytics;使用 Firebase.Core;使用基金会;使用 MobileApp.Services;命名空间 MobileApp.iOS.Services{[组装:依赖(typeof(AnalyticsServiceIOS))]公共类 AnalyticsServiceIOS : IAnalyticsService{public void LogEvent(string eventId){LogEvent(eventId, (IDictionary)null);}public void LogEvent(string eventId, string paramName, string value){LogEvent(eventId, new Dictionary;{{参数名称,值}});}public void LogEvent(string eventId, IDictionary parameters){//修复eventId的实用方法,如果你确定总是传递有效的eventIds,你可以跳过它eventId = FixEventId(eventId);如果(参数==空){Analytics.LogEvent(eventId, 参数: null);返回;}var keys = new List();var values = new List();foreach(参数中的var item){键.添加(新 NSString(项目.键));values.Add(new NSString(item.Value));}var 参数字典 =NSDictionary.FromObjectsAndKeys(values.ToArray(), keys.ToArray(), keys.Count);Analytics.LogEvent(eventId, parametersDictionary);}//修复eventId的实用方法,如果你确定总是传递有效的eventIds,你可以跳过它私有字符串 FixEventId(字符串 eventId){if (string.IsNullOrWhiteSpace(eventId))返回未知";//删除不需要的字符eventId = Regex.Replace(eventId, @"[^a-zA-Z0-9_]+", "_", RegexOptions.Compiled);//如果需要,修剪到40return 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{公共 MenuPageViewModel(){var analyticsService= DependencyService.Get();//您可以使用任何 LogEvent 重载,例如:analyticsService.LogEvent("事件");}}
Can we get custom events such as say Button 1 was pressed using Firebase Analytics in a Xamarin Forms Project ?
Answer Updated for the new version of Xamarin Firebase components and to fix various issues
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 Project
- Xamarin.FireBase.Analytics
- Xamarin.FireBase.Analytics.Impl
- Plugin.CurrentActivity (used to get the current context as
Forms.Context
is deprecated)
iOS Project
- Xamarin.FireBase.iOS.Analytics (iOS project)
In your PCL (or .NETStandard) project create the interface
- In the Android and iOS project write the plaftorm specific code
- In your viewmodels, use DI in the PCL (or .NETStandard) project to call the
LogEvent
method to store your event
Note: Custom events are slow to appear in firebase, in my experience they need 24 hours to appear in the web console. If you want to properly test the custom logging, use your phone and activate the analytics debug (so you can see your events in the debugView in firebase console)*
Note2: watch out for the
eventId
property: names can be up to 40 characters long, may only contain alphanumeric characters and underscores (""), and must start with an alphabetic character. The "firebase", "google_" and "ga_" prefixes are reserved and should not be used. I have included a smal utility function to automatically fix eventId, you can skip it if you want
PCL or .NETStandard project
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
Make sure to have the INTERNET permission in your manifest.
Import your google-services.json (generated from your firebase account) with compilation action set to "GoogleServicesJson"
Remember to call CrossCurrentActivity
init method in your AppDelegate OnCreate
:
CrossCurrentActivity.Current.Init(this, bundle);
This is the Android platform service code:
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));
}
}
}
Debug View in Android
To enable the debugView in the firebase run this command from your adb console command prompt (usually is c:WINDOWSSystem32
, but you can reach it through Visual Studio in tools --> android --> android adb command prompt
):
adb shell setprop debug.firebase.analytics.app <package_name>
To disable the debugView use:
adb shell setprop debug.firebase.analytics.app .none.
Verbose logging
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.
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
Important note
Some external libraries (Like MS AppCenter) are already including Firebase and explicitly disabling analytics in teir manifest.
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"/>
Also make sure to have this property inside your
<manifest>
tag:xmlns:tools="http://schemas.android.com/tools"
iOS
Make sure to test the event logging on your phone! This is not going to work anymore on emulators
Initialize the component in your AppDelegate, just before base.FinishedLaunching:
Firebase.Core.App.Configure();
Then import your GoogleService-Info.plist (generated from your firebase account) with compilation action set to "BundleResource" .
This is the iOS platform service code:
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));
}
}
}
Debug View in iOS
To enable the debugView in the firebase console add the following argument to Extra mlaunch Arguments in your iOS project properties:
--argument=-FIRDebugEnabled
To disable the debugView use:
--argument=-FIRDebugDisabled
Important note (thanks to Ken for pointing out this)
If you get an exception calling
Firebase.Core.App.Configure();
in your AppDelegate, modify yourGoogleService-Info.plist
settingsIS_ANALYTICS_ENABLED
totrue
In your ViewModel you can track any event you want
For Example:
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 分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!