1
votes

I am try to use Facebook and Firebase Unity plugin to implement User authentication in android platform. After I pass facebook login and want to get firebase Credential use facebook token, application crashed. I can find information from androidstudio logcat:"A/firebase: Firebase Auth was not initialized, unable to create a Credential. Create an Auth instance first.". It seems Firebase Auth need some initialized. But I have see Firebase Unity document and can not find any initialize information. Any help will be appreciated.

I use Unity 2018.3.8f1, facebook-unity-sdk-7.15.1 and firebase_unity_sdk_5.6.0. because Facebook Unity SDK can not run in Unity editor, so I always build apk througe Unity editor and try it in an android emulator.

This is my C# code(Unity script), nearly all use example code from firebase document:

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

This is error log find from 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
try to uncomment this code snippet app = Firebase.FirebaseApp.DefaultInstanceMathieuAuclair

1 Answers

0
votes

// auth = Firebase.Auth.FirebaseAuth.DefaultInstance; try to uncomment this code

This code initialize firebase auth.