Когда я использую плагин Firebase Unity для реализации функции FaceBook Auth в Android, происходит сбой

#firebase #unity3d #firebase-authentication

#firebase #unity3d #firebase-аутентификация

Вопрос:

Я пытаюсь использовать Facebook и плагин Firebase Unity для реализации аутентификации пользователя на платформе Android. После того, как я передаю facebook login и хочу получить учетные данные firebase, используя facebook token, произошел сбой приложения. Я могу найти информацию из androidstudio logcat: «A / firebase: Firebase 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, поэтому я всегда создаю apk через редактор Unity и пробую его в эмуляторе 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.Resu<
            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 amp;amp; senderAuth.CurrentUser != user) 
        {
            bool signedIn = user != senderAuth.CurrentUser amp;amp; senderAuth.CurrentUser != null;
            if (!signedIn amp;amp; 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.Resu<
                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>
  

Комментарии:

1. попробуйте раскомментировать этот фрагмент кода app = Firebase.FirebaseApp.DefaultInstance

Ответ №1:

// auth = Firebase.Auth.FirebaseAuth.DefaultInstance; попробуйте раскомментировать этот код

Этот код инициализирует firebase auth.

Комментарии:

1. Спасибо. Ваш ответ очень полезен, auth = Firebase.Auth. FirebaseAuth. DefaultInstance — это работа. и я нахожу настоящую причину в том, что я должен написать эту строку, когда Firebase. FirebaseApp. Проверка и исправление зависимостей в синхронизации выполняется успешно. Кажется, что перед успешной проверкой CheckAndFixDependenciesAsync произойдет сбой get auth.