iOS 接入firebase简易步骤
Posted chengqiang0414
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 接入firebase简易步骤相关的知识,希望对你有一定的参考价值。
接入准备
去firebase官网注册应用并下载配置文件GoogleService-Info.plist
接入步骤
1.通过cocopods导入以下两个依赖
pod 'Firebase/Analytics'
pod 'Firebase/Core'
2.导入成功后将配置文件GoogleService-Info.plist拖入项目中
3.代码支持
引入#import <Firebase/Firebase.h>
1.初始化配置
在 - (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions 中
执行[FIRApp configure];
2.设置默认信息(内容可自定义,会在每个事件上报)
[FIRAnalytics setDefaultEventParameters:@@"key1":@"value1",@"key2":@"value2"];
3.事件上报(内容都可自定义)
[FIRAnalytics logEventWithName:@"eventName"
parameters:@@"key1":@"value1",@"key2":@"value2"];
4.调试配置
需要在xcode菜单条中Product->Scheme->Edit Scheme->Arguments Passed On Luanch 中添加以下配置!前面的杠符号也要!!!!
-FIRAnalyticsDebugEnabled
-FIRAnalyticsVerboseLoggingEnabled
-FIRDebugEnabled
以上配置完了插上手机run才能在firebase后台的debugview中看到实时事件!但是打包ipa直接安装是不可以测试事件的!
测试事件
需要将打包好的ipa上传到firebase后台中的App Distribution中 添加测试员的邮箱 测试员通过邮箱中的邀请链接下载才会有事件上报效果!
可在Firebase的Realtime中查看事件
Unity 接入Firebase第三方登录(AppleFacebookGoogle)
目录
一、 Firebase接入
1. SDK下载
官方网址: firebase官网
图片中1为demo地址,2为SDK包
2. 接入准备工作
此为firebase的unity包,根据自身需求接入对应的,对应关系如下
3. firebase初始化
public class FireBase : MonoBehaviour
Firebase.FirebaseApp app;
Firebase.Auth.FirebaseAuth auth;
private bool firebaseInitialized;
// Start is called before the first frame update
IEnumerator Start()
InitializeFirebaseAndStart();
while (!firebaseInitialized)
yield return null;
auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
// 初始化firebase
void InitializeFirebaseAndStart()
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
var dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available)
firebaseInitialized = true;
Debug.Log("firebase Initialized");
else
Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
// Application.Quit();
);
4. 登录接入文档
在此介绍三种第三方登录,根据官方文档提示,Apple、Google、Facebook 都需要再接入sdk获取token,然后使用firebase的验证获取firebase的token。
二、 Google 登录接入
注意:本文介绍的是google登录,而非google-play-game登录
1. 插件介绍
在此推荐一个插件 google-signin,地址为: google-signin
打包测试,Android测试成功,但是iOS会报如下错误
官方推荐是使用老版本,地址如下:https://github.com/googlesamples/google-signin-unity/issues/102,可供参考
因为我使用的sdk都是新版本,在此选择升级,升级后的地址如下
地址:使用google 6.0.0 以上版本地址
2. 初始化
GoogleSignIn.Configuration = new GoogleSignInConfiguration
RequestIdToken = true,
// Copy this value from the google-service.json file.
// oauth_client with type == 3
//填入在配置谷歌项目SHA1值时给你的Client ID
WebClientId = " "
;
3. 登录请求
public void GoogleLogin()
Debug.Log("Enter Google Script Login Method");
Task<GoogleSignInUser> signIn = GoogleSignIn.DefaultInstance.SignIn();
signIn.ContinueWithOnMainThread(task =>
if (task.IsCanceled)
Debug.Log("task.IsCanceled");
else if (task.IsFaulted)
Debug.Log("task.IsFaulted = " + task.Exception.Message);
else
var idToken = ((Task<GoogleSignInUser>)task).Result.IdToken;
Debug.Log("idToken = " + idToken);
Credential credential = Firebase.Auth.GoogleAuthProvider.GetCredential(idToken, null);
CredentialSigin(credential);
);
4. firebase 登录验证
三种登录方式都用此方法验证
public void CredentialSigin(Credential credential)
auth.SignInWithCredentialAsync(credential).ContinueWith(async authTask =>
if (authTask.IsCanceled)
Debug.Log("authTask.IsCanceled");
// if (LoginResultManager.Instance != null)
// LoginResultManager.Instance.OpenLoginResult(false);
// signInCompleted.SetCanceled();
else if (authTask.IsFaulted)
Debug.Log("authTask.IsFaulted");
// if (LoginResultManager.Instance != null)
// LoginResultManager.Instance.OpenLoginResult(false);
// signInCompleted.SetException(authTask.Exception);
else
// signInCompleted.SetResult(((Task<FirebaseUser>)authTask).Result);
Firebase.Auth.FirebaseUser newUser = authTask.Result;
Debug.Log(String.Format("User Login Successful : 0 (1)", newUser.DisplayName, newUser.UserId));
var token = await newUser.TokenAsync(true);
Debug.Log("Firebase Token = " + token);
// 访问服务器
action_fbToken?.Invoke(token);
);
三、FaceBook 登录接入
1. 插件介绍
地址:facebook
2. 接入设置
导入相关unity包后,根据下图所示填入信息
3. 初始化
public void InitializeFacebook()
if (!FB.IsInitialized)
// Initialize the Facebook SDK
FB.Init(InitCallback, OnHideUnity);
else
// Already initialized, signal an app activation App Event
FB.ActivateApp();
private void InitCallback()
if (FB.IsInitialized)
// Signal an app activation App Event
FB.ActivateApp();
// Continue with Facebook SDK
// ...
else
Debug.Log("Failed to Initialize the Facebook SDK");
private void OnHideUnity(bool isGameShown)
if (!isGameShown)
// Pause the game - we will need to hide
Time.timeScale = 0;
else
// Resume the game - we're getting focus again
Time.timeScale = 1;
4. 登录请求
public void FacebookLogin()
if (FB.IsInitialized)
var perms = new List<string>() "public_profile", "email" ;
FB.LogInWithReadPermissions(perms, AuthCallback);
else
Debug.Log("Not Init");
private void AuthCallback(ILoginResult result)
if (result.Error != null)
Debug.Log("Error: " + result.Error);
else
if (FB.IsLoggedIn)
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log("aToken.UserId: " + aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions)
Debug.Log("perm: " + perm);
var idToken = aToken.TokenString;
Credential credential = Firebase.Auth.FacebookAuthProvider.GetCredential(idToken);
CredentialSigin(credential);
else
Debug.Log("User cancelled login");
5. firebase登录验证
同Google登录接入的第四步
四、 Apple登录接入
1. 插件介绍
推荐使用此插件,此插件也是官方文档中提到的插件
GitHub地址: Sign in with Apple Unity Plugin
2. 接入设置
根据文档添加后处理文件
3. 初始化
private IAppleAuthManager _appleAuthManager;
void InitializeApple()
if (AppleAuthManager.IsCurrentPlatformSupported)
// Creates a default JSON deserializer, to transform JSON Native responses to C# instances
var deserializer = new PayloadDeserializer();
// Creates an Apple Authentication manager with the deserializer
this._appleAuthManager = new AppleAuthManager(deserializer);
void Update()
// Updates the AppleAuthManager instance to execute
// pending callbacks inside Unity's execution loop
if (this._appleAuthManager != null)
this._appleAuthManager.Update();
4. 登录请求
public void AppleLogin()
var rawNonce = GenerateRandomString(32);
var nonce = GenerateSHA256NonceFromRawNonce(rawNonce);
var loginArgs = new AppleAuthLoginArgs(LoginOptions.IncludeEmail | LoginOptions.IncludeFullName, nonce);
this._appleAuthManager.LoginWithAppleId(
loginArgs,
credential =>
// Obtained credential, cast it to IAppleIDCredential
var appleIdCredential = credential as IAppleIDCredential;
if (appleIdCredential != null)
// Apple User ID
// You should save the user ID somewhere in the device
var userId = appleIdCredential.User;
Debug.Log("app userId = " + userId);
// PlayerPrefs.SetString(AppleUserIdKey, userId);
// Email (Received ONLY in the first login)
var email = appleIdCredential.Email;
Debug.Log("app email = " + email);
// Full name (Received ONLY in the first login)
var fullName = appleIdCredential.FullName;
Debug.Log("app fullName = " + fullName);
// Identity token
var identityToken = Encoding.UTF8.GetString(
appleIdCredential.IdentityToken,
0,
appleIdCredential.IdentityToken.Length);
Debug.Log("app identityToken = " + identityToken);
// Authorization code
var authorizationCode = Encoding.UTF8.GetString(
appleIdCredential.AuthorizationCode,
0,
appleIdCredential.AuthorizationCode.Length);
Debug.Log("app authorizationCode = " + authorizationCode);
// And now you have all the information to create/login a user in your system
Credential FirebaseCredential = Firebase.Auth.OAuthProvider.GetCredential("apple.com", identityToken, rawNonce, authorizationCode);
CredentialSigin(FirebaseCredential);
,
error =>
var authorizationErrorCode = error.GetAuthorizationErrorCode();
Debug.LogWarning("Sign in with Apple failed " + authorizationErrorCode.ToString() + " " + error.ToString());
);
5. firebase登录验证
同Google登录接入的第四步
五、结语
希望大家都可以成功接入,有任何问题欢迎评论区提问。
以上是关于iOS 接入firebase简易步骤的主要内容,如果未能解决你的问题,请参考以下文章
(Firebase Xcode 12 iOS 14)如何正确调用和设置孩子?
Xcode 10 iOS firebase firestore SDK -- 多个命令在 Firebase 中产生 gRPCCertificates.bundle 错误
Firebase 动态链接无法从冷启动 - Xcode 11,iOS 13