firebase - 当我使用Firebase Unity插件在android中实现FaceBook Auth功能时,它崩溃了

标签 firebase unity-game-engine firebase-authentication

我尝试使用Facebook和Firebase Unity插件在android平台上实现用户身份验证。在我通过 facebook 登录并想要使用 facebook token 获取 firebase 凭据后,应用程序崩溃了。我可以从androidstudio logcat找到信息:“A/firebase:Firebase Auth未初始化,无法创建凭据。首先创建一个Auth实例。”。看来 Firebase Auth 需要一些初始化。但我看过 Firebase Unity 文档,找不到任何初始化信息。任何帮助将不胜感激。

我使用 Unity 2018.3.8f1、facebook-unity-sdk-7.15.1 和 firebase_unity_sdk_5.6.0。因为Facebook Unity SDK无法在Unity编辑器中运行,所以我总是通过Unity编辑器构建apk并在android模拟器中尝试。

这是我的 C# 代码(Unity 脚本),几乎全部使用 firebase 文档中的示例代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Facebook.Unity;
using Firebase.Auth;

public class LoginWithFB : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    public Firebase.Auth.FirebaseAuth auth;
    void Awake ()
    {
        Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => 
        {
            var dependencyStatus = task.Result;
            if (dependencyStatus == Firebase.DependencyStatus.Available) 
            {
                // Create and hold a reference to your FirebaseApp,
                // where app is a Firebase.FirebaseApp property of your application class.
                //   app = Firebase.FirebaseApp.DefaultInstance;

                // Set a flag here to indicate whether Firebase is ready to use by your app.
                InitializeFirebase();
            } 
            else 
            {
                UnityEngine.Debug.LogError(System.String.Format("Could not resolve all Firebase dependencies: {0}", dependencyStatus));
                // Firebase Unity SDK is not safe to use here.
            }
        });

        if (!FB.IsInitialized) {
            // Initialize the Facebook SDK
            FB.Init(InitCallback, OnHideUnity);
        } else {
            // Already initialized, signal an app activation App Event
            FB.ActivateApp();
        }
        //auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
    }

    protected void InitializeFirebase() 
    {
        //DebugLog("Setting up Firebase Auth");
        auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
        auth.StateChanged += AuthStateChanged;
        //auth.IdTokenChanged += IdTokenChanged;
        // Specify valid options to construct a secondary authentication object.
        AuthStateChanged(this, null);
    }

    void AuthStateChanged(object sender, System.EventArgs eventArgs) 
    {
        Firebase.Auth.FirebaseAuth senderAuth = sender as Firebase.Auth.FirebaseAuth;
        Firebase.Auth.FirebaseUser user = null;
        //if (senderAuth != null) userByAuth.TryGetValue(senderAuth.App.Name, out user);
        if (senderAuth == auth && senderAuth.CurrentUser != user) 
        {
            bool signedIn = user != senderAuth.CurrentUser && senderAuth.CurrentUser != null;
            if (!signedIn && user != null) 
            {
                Debug.Log("Signed out " + user.UserId);
            }
            user = senderAuth.CurrentUser;
            //userByAuth[senderAuth.App.Name] = user;
            if (signedIn) 
            {
                Debug.Log("Signed in " + user.UserId);
                //displayName = user.DisplayName ?? "";
                //DisplayDetailedUserInfo(user, 1);
            }
        }
    }

    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;
        }
    }
    private void AuthCallback (ILoginResult result) 
    {
        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);
            Debug.Log(aToken.TokenString);
            Debug.Log(auth);
            // Print current access token's granted permissions
            foreach (string perm in aToken.Permissions) 
            {
                Debug.Log(perm);
            }

            Firebase.Auth.Credential credential = Firebase.Auth.FacebookAuthProvider.GetCredential(aToken.TokenString);
            //auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => 
            {
                if (task.IsCanceled) 
                {
                    Debug.LogError("SignInWithCredentialAsync was canceled.");
                    return;
                }
                if (task.IsFaulted) 
                {
                    Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
                    return;
                }

                Firebase.Auth.FirebaseUser newUser = task.Result;
                Debug.LogFormat("User signed in successfully: {0} ({1})",
                    newUser.DisplayName, newUser.UserId);
            });

            Debug.Log("Ready goto AsterPlayMainScene");
            Application.LoadLevel("AsterPlayMainScene");
            //SceneManager.LoadScene("AsterPlayMainScene");

        } 
        else 
        {
            Firebase.Auth.Credential credential = Firebase.Auth.FacebookAuthProvider.GetCredential("asadjkahfidhfahfguisodhui");

            Debug.Log("User cancelled login");
            Application.LoadLevel("AsterPlayMainScene");
            //SceneManager.LoadScene("AsterPlayMainScene");
        }
    }

    public void OnFBLoginClick()
    {
        var perms = new List<string>(){"public_profile", "email"};
        FB.LogInWithReadPermissions(perms, AuthCallback);
    }
}

这是从 android studio logcat 找到的错误日志:

2019-03-31 22:22:25.313 20155-20186/? E/firebase: g_methods_cached
2019-03-31 22:22:25.313 20155-20186/? A/firebase: Firebase Auth was not initialized, unable to create a Credential. Create an Auth instance first.

Also I can find callstack from logcat:
2019-03-31 22:22:25.548 20155-20186/? E/CRASH:  #32  il 00000012  at (wrapper managed-to-native) Firebase.Auth.AuthUtilPINVOKE.FacebookAuthProvider_GetCredential (string) <0x00012>
2019-03-31 22:22:25.548 20155-20186/? E/CRASH:  #33  il 00000013  at Firebase.Auth.FacebookAuthProvider.GetCredential (string) [0x00000] in <7ff3b01c54e9444eb36c9f4350522434>:0
2019-03-31 22:22:25.548 20155-20186/? E/CRASH:  #34  il 000000eb  at LoginWithFB.AuthCallback (Facebook.Unity.ILoginResult) [0x00064] in <9cb866e367a54ac3882a6e4448a28c2e>:0
2019-03-31 22:22:25.548 20155-20186/? E/CRASH:  #35  il 00000069  at Facebook.Unity.CallbackManager.TryCallCallback<Facebook.Unity.ILoginResult> (object,Facebook.Unity.IResult) [0x0000a] in <8c4c3b91cd24414db7bdbc53fc97f955>:0
2019-03-31 22:22:25.548 20155-20186/? E/CRASH:  #36  il 000000f3  at Facebook.Unity.CallbackManager.CallCallback (object,Facebook.Unity.IResult) [0x00046] in <8c4c3b91cd24414db7bdbc53fc97f955>:0
2019-03-31 22:22:25.548 20155-20186/? E/CRASH:  #37  il 00000077  at Facebook.Unity.CallbackManager.OnFacebookResponse (Facebook.Unity.IInternalResult) [0x00021] in <8c4c3b91cd24414db7bdbc53fc97f955>:0
2019-03-31 22:22:25.548 20155-20186/? E/CRASH:  #38  il 00000033  at Facebook.Unity.FacebookBase.OnAuthResponse (Facebook.Unity.LoginResult) [0x00019] in <8c4c3b91cd24414db7bdbc53fc97f955>:0
2019-03-31 22:22:25.548 20155-20186/? E/CRASH:  #39  il 0000003c  at Facebook.Unity.Mobile.MobileFacebook.OnLoginComplete (Facebook.Unity.ResultContainer) [0x00007] in <8c4c3b91cd24414db7bdbc53fc97f955>:0
2019-03-31 22:22:25.549 20155-20186/? E/CRASH:  #40  il 00000046  at Facebook.Unity.FacebookGameObject.OnLoginComplete (string) [0x0000c] in <8c4c3b91cd24414db7bdbc53fc97f955>:0
2019-03-31 22:22:25.549 20155-20186/? E/CRASH:  #41  il 0000005b  at (wrapper runtime-invoke) <Module>.runtime_invoke_void__this___object (object,intptr,intptr,intptr) <0x0005b>

最佳答案

//auth = Firebase.Auth.FirebaseAuth.DefaultInstance; 尝试取消此代码的注释

此代码初始化 firebase 身份验证。

关于firebase - 当我使用Firebase Unity插件在android中实现FaceBook Auth功能时,它崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55442088/

相关文章:

Android - 警报对话框后 map 重复

java - 根据变量的值对变量进行分类

c# - 哪个函数用于使用 Unity 地形引擎绘制地形?

user-interface - Unity 4.6 的 GUI - 检测 Click() Down

ios - swift - firebase facebook 身份验证时出现 invalid_credentials 错误?

java - firebase.auth.PhoneAuthProvider 缺失

javascript - 将 Excel 上传到 Google Cloud Storage 时出错

javascript - 在 Nuxt JS 中创建 Vue 应用程序之前检查 Firebase onAuthStateChanged

c++ - iOS集成unity 4.6.3项目(64位&& IL2CPP)。出现如下这样的错误,如何解决呢?

android - com.google.firebase.FirebaseException : An internal error has occurred. [ CONFIGURATION_NOT_FOUND ]