Open Nicokkam opened 3 years ago
I Decided to add the codes I am using too. Both of them are added to the same GameObject in unity. Here they are:
`using System.Collections; using UnityEngine; using Firebase; using Firebase.Auth; using TMPro; using Facebook.Unity;
public class AuthManager : MonoBehaviour{ //Firebase variables [Header("Firebase")] public DependencyStatus dependencyStatus; public FirebaseAuth auth; public FirebaseUser User;
//Login variables [Header("Login")] public TMP_InputField emailLoginField; public TMP_InputField passwordLoginField; public TMP_Text warningLoginText; public TMP_Text confirmLoginText;
//Register variables [Header("Register")] public TMP_InputField usernameRegisterField; public TMP_InputField emailRegisterField; public TMP_InputField passwordRegisterField; public TMP_InputField passwordRegisterVerifyField; public TMP_Text warningRegisterText;
void Awake() { //Check that all of the necessary dependencies for Firebase are present on the system FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>{ dependencyStatus = task.Result; if (dependencyStatus == DependencyStatus.Available){ //If they are avalible Initialize Firebase InitializeFirebase(); } else { Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus); } }); }
private void InitializeFirebase() { Debug.Log("Setting up Firebase Auth"); //Set the authentication instance object auth = FirebaseAuth.DefaultInstance; auth.StateChanged += AuthStateChanged; AuthStateChanged(this, null); }
private void OnDestroy(){ auth.StateChanged -= AuthStateChanged; auth = null; }
public void LoginButton() { Login(emailLoginField.text, passwordLoginField.text); }
public void RegisterButton(){ StartCoroutine(Register(emailRegisterField.text, passwordRegisterField.text, usernameRegisterField.text)); }
public void Login(string _email, string _password){ var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password); LoginTask.ContinueWith(task => { if (task.IsCanceled || task.IsFaulted) { Firebase.FirebaseException e = task.Exception.Flatten().InnerExceptions[0] as Firebase.FirebaseException; GetErrorMessage((AuthError)e.ErrorCode, warningLoginText); return; }
if (task.IsCompleted) {
User = LoginTask.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
warningLoginText.text = "";
confirmLoginText.text = "Logged In";
UIControllerLogin.instance.MainScreenScene();
}
});
}
public IEnumerator Register(string _email, string _password, string _username) { if (_username == "") { //If the username field is blank show a warning warningRegisterText.text = "Missing Username"; } else if (passwordRegisterField.text != passwordRegisterVerifyField.text) { //If the password does not match show a warning warningRegisterText.text = "Password Does Not Match!"; } else { //Call the Firebase auth signin function passing the email and password var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password); //Wait until the task completes yield return new WaitUntil(predicate: () => RegisterTask.IsCompleted);
if (RegisterTask.Exception != null) {
//If there are errors handle them
FirebaseException e =
RegisterTask.Exception.Flatten().InnerExceptions[0] as FirebaseException;
GetErrorMessage((AuthError)e.ErrorCode, warningRegisterText);
}
else {
//User has now been created
//Now get the result
User = RegisterTask.Result;
if (User != null) {
//Create a user profile and set the username
UserProfile profile = new UserProfile { DisplayName = _username };
//Call the Firebase auth update user profile function passing the profile with the username
var ProfileTask = User.UpdateUserProfileAsync(profile);
//Wait until the task completes
yield return new WaitUntil(predicate: () => ProfileTask.IsCompleted);
if (ProfileTask.Exception != null) {
//If there are errors handle them
Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
warningRegisterText.text = "Username Set Failed!";
}
else {
//Username is now set
//Now return to login screen
UIControllerLogin.instance.LoginScreenActive();
warningRegisterText.text = "";
}
}
}
}
}
void AuthStateChanged(object sender, System.EventArgs eventArgs) { if (auth.CurrentUser != User) { bool signedIn = User != auth.CurrentUser && auth.CurrentUser != null; if (!signedIn && User != null) { Debug.Log("Signed out " + User.UserId); UIControllerLogin.instance.LoginScene(); } User = auth.CurrentUser; if (signedIn) { Debug.Log("Signed in " + User.UserId); UIControllerLogin.instance.MainScreenScene(); string displayName = User.DisplayName ?? ""; string emailAddress = User.Email ?? ""; // string photoUrl = User.PhotoUrl ?? ""; string uid = User.UserId ?? ""; } } }
void GetErrorMessage(AuthError errorCode, TMP_Text INFText) { string msg = ""; msg = errorCode.ToString();
switch (errorCode) {
case AuthError.InvalidEmail:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/InvalidEmailOrPSW");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/InvalidEmailOrPSW"));
break;
case AuthError.WrongPassword:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/InvalidEmailOrPSW");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/InvalidEmailOrPSW"));
break;
case AuthError.AccountExistsWithDifferentCredentials:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/DiffCredentials");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/DiffCredentials"));
break;
case AuthError.MissingPassword:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/MissingPSW");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/MissingPSW"));
break;
case AuthError.MissingEmail:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/MissingEmail");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/MissingEmail"));
break;
case AuthError.EmailAlreadyInUse:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/EmailInUse");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/EmailInUse"));
break;
case AuthError.TooManyRequests:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/ManyRequests");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/ManyRequests"));
break;
case AuthError.SessionExpired:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/SessionExpired");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/SessionExpired"));
break;
case AuthError.WeakPassword:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/WeakPSW");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/WeakPSW"));
break;
case AuthError.UserNotFound:
INFText.text =
Lean.Localization.LeanLocalization.GetTranslationText($"Login/UserNotFound");
print(Lean.Localization.LeanLocalization.GetTranslationText($"Login/UserNotFound"));
break;
default:
print($"errorCode: {msg}");
break;
}
}
public void loginviaFirebaseFacebook(AccessToken accessToken) { Firebase.Auth.Credential credential = Firebase.Auth.FacebookAuthProvider.GetCredential(accessToken.TokenString); auth.SignInWithCredentialAsync(credential).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SignInWithCredentialAsync was canceled."); warningLoginText.text = "SignInWithCredentialAsync was canceled"; return; } if (task.IsFaulted) { Debug.LogError($"SignInWithCredentialAsync encountered an error: {task.Exception}"); warningLoginText.text = $"SignInWithCredentialAsync encountered an error: {task.Exception}"; return; }
User = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.UserId);
UIControllerLogin.instance.MainScreenScene();
});
}
} `
`using System.Collections; using System.Collections.Generic; using UnityEngine; using Firebase.Auth; using Facebook.Unity;
public class FacebookInit : MonoBehaviour { private AuthManager AuthManagercs;
// Start function from Unity's MonoBehavior
void Start() {
AuthManagercs = GetComponent
if (!FB.IsInitialized) {
FB.Init(initCallback, onHideUnity);
}
else {
// Already initialized
FB.ActivateApp();
}
}
private void initCallback() { if (FB.IsInitialized) { // Signal an app activation App Event FB.ActivateApp(); // Continue with Facebook SDK // ... } else { Debug.Log("Something went wrong to Initialize the Facebook SDK"); } }
private void onHideUnity(bool isGameScreenShown) { if (!isGameScreenShown) { // Pause the game - we will need to hide Time.timeScale = 0; } else { // Resume the game - we're getting focus again Time.timeScale = 1; } }
public void FacebookButton() {
// Permission option list https://developers.facebook.com/docs/facebook-login/permissions/
var permissons = new List
private void authStatusCallback(ILoginResult result) { if (FB.IsLoggedIn) { // AccessToken class will have session details AccessToken accessToken = Facebook.Unity.AccessToken.CurrentAccessToken; // current access token's User ID : aToken.UserId AuthManagercs.loginviaFirebaseFacebook(accessToken); } else { Debug.Log("User cancelled login"); } } } `
@Nicokkam if you read through the error log you see fx.
FBSDKLog: fb-messenger-share-api is missing from your Info.plist under LSApplicationQueriesSchemes and is required.
This means that you are missing this definition in the Info.plist, it's available under the Info section in Xcode for Unity-iPhone (main target)
If you open that up you can create the data if you don't already have it. It seems that this fb-messenger-share-api is something related to iOS 9. Could it be your project in Unity is set to iOS 9 but Xcode to higher? Not that it should matter.
I would try to add this to the LSApplicationQueriesSchemes. You most likely have some data there, if not then create an Array and name it LSApplicationQueriesSchemes. See the attached image. I however don't support iOS 9 but you should create new string called fb-messenger-share-api under the LSApplicationQueriesSchemes array.
@snorrsi
Thanks for coming to the rescue again. Just did what you asked and I am building the project, will tell you if it worked soon.
Going to check the iOS9 thing, but I doubt it... last time I checked It was 11
Didn't work....
And as I said, It is targeted to iOS 11.0 minimum.
@Nicokkam it´s often good to try to remove errors. Maybe you should remove the setting I mentioned, facebook might try to use it if it doesn´t check your iOS version.
Regarding next steps I would build a Development Build from Unity and run your app on your device in debug mode catching all Exceptions from Xcode. You can also try to pinpoint excectly where you are getting the error by adding try .. catch or debug log in the C# code. See if your firebase settings are correct. You could check in Xcode if Google-Services.plist is added to your project, the target should be UnityFramework and Unity-iPhone
any updates here?
Checklist
Environment
Describe your dev environment here, giving as many details as possible. If you have them, make sure to include:
Unity Editor Version: 2020.1.0f1 Unity SDK Version: 8.1.1 Installation Platform & Version: iOS|Android version (?)
[REQUIRED] Please fill in the following fields:
Unity editor version: 2020.1.0f1 Firebase Unity SDK version: Latest Source you installed the SDK: .unitypackage Problematic Firebase Component: Database Other Firebase Components in use: Auth, Database and Analytics Additional SDKs you are using: Facebook Platform you are using the Unity editor on: Mac Platform you are targeting: iOS, Android Scripting Runtime: _____ IL2CPP
[REQUIRED] Please describe the issue here:
I am having so much trouble with this SDK! I just came across another bug that I cannot solve.
So, I added the Firebase and Facebook SDK's in my unity project and something weird happened.
My code works perfectly in the Unity Editor (Email/Password and Facebook Login) with no errors whatsoever. BUT, when I build it into iOS and try it out on my code, nothing regarding the SDK works, not even the button that makes the login (It should activate a message that says that I have to fill out the email field, etc..). Even if I fill out the information it doesn't do anything. The facebook button does trigger the login process, but when it comes to the end and starts to return from the facebook app to mine, it just returns to the login screen as if nothing had happened (It should go to the main screen instead).
As I said in the beginning, everything IS WORKING PERFECTLY in the editor, so I'm guessing It's something not very complex but specific that I don't have to knowledge solve on my own, given that I have dedicated all day on this matter.
Would really appreciate some help and please don't hesitate to ask for information that will help to accelerate this process.
Here is the other post I made (don't know if I modified something I shouldn't): https://github.com/facebook/facebook-sdk-for-unity/issues/504
Here are some of the errors from the Xcode:
CrashReporter: initialized 2020-12-17 19:49:32.185064-0300 zzzz[23059:8122575] Built from '2020.1/staging' branch, Version '2020.1.0f1 (2ab9c4179772)', Build type 'Release', Scripting Backend 'il2cpp' -> applicationDidFinishLaunching() 2020-12-17 19:49:32.257870-0300 zzzz[23059:8122575] Metal GPU Frame Capture Enabled 2020-12-17 19:49:32.258456-0300 zzzz[23059:8122575] Metal API Validation Enabled -> applicationDidBecomeActive() [Subsystems] Discovering subsystems at path /private/var/containers/Bundle/Application/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY/Data/UnitySubsystems GfxDevice: creating device client; threaded=1 Initializing Metal device caps: Apple A13 GPU Initialize engine version: 2020.1.0f1 (2ab9c4179772) CrashReporter: Could not parse crash report: Could not decode truncated crash log 2020-12-17 19:49:33.811029-0300 moovyn[23059:8122924] [Client] Updating selectors after delegate removal failed with: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service on pid 92 named com.apple.commcenter.coretelephony.xpc was invalidated from this process." UserInfo={NSDebugDescription=The connection to service on pid 92 named com.apple.commcenter.coretelephony.xpc was invalidated from this process.} 2020-12-17 19:49:33.814584-0300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[23059:8122575] Unbalanced calls to begin/end appearance transitions for <UnityViewControllerStoryboard: 0x103487ac0>. 2020-12-17 19:49:33.823953-0300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[23059:8122919] [tcp] tcp_input [C2.1:3] flags=[R] seq=265141129, ack=0, win=0 state=CLOSED rcv_nxt=265141129, snd_una=1607627885 2020-12-17 19:49:33.824001-0300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[23059:8122919] [tcp] tcp_input [C2.1:3] flags=[R] seq=265141129, ack=0, win=0 state=CLOSED rcv_nxt=265141129, snd_una=1607627885 2020-12-17 19:49:33.849809-0300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[23059:8122923] FBSDKLog: fb-messenger-share-api is missing from your Info.plist under LSApplicationQueriesSchemes and is required. 2020-12-17 19:49:33.858905-0300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[23059:8122924] [tcp] tcp_input [C3.1:3] flags=[R] seq=2668679344, ack=0, win=0 state=CLOSED rcv_nxt=2668679344, snd_una=1421442049 2020-12-17 19:49:33.858980-0300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[23059:8122924] [tcp] tcp_input [C3.1:3] flags=[R] seq=2668679344, ack=0, win=0 state=CLOSED rcv_nxt=2668679344, snd_una=1421442049 2020-12-17 19:49:34.978091-0300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[23059:8122919] [tcp] tcp_input [C4.2:3] flags=[R] seq=4236490899, ack=0, win=0 state=CLOSED rcv_nxt=4236490899, snd_una=2789091866 2020-12-17 19:49:34.978937-0300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX[23059:8122919] [tcp] tcp_input [C4.2:3] flags=[R] seq=4236490899, ack=0, win=0 state=CLOSED rcv_nxt=4236490899, snd_una=2789091866 UnloadTime: 4.260792 ms Setting up Firebase Auth UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object) UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[]) UnityEngine.Logger:Log(LogType, Object) UnityEngine.Debug:Log(Object) AuthManager:InitializeFirebase() AuthManager:<Awake>b__12_0(Task
1) System.Action1:Invoke(T) System.Threading.Tasks.ContinuationTaskFromResultTask
1:InnerInvoke() System.Threading.Tasks.Task:Execute() System.Threading.Tasks.Task:ExecutionContextCallback(Object) System.Threading.ContextCallback:Invoke(Object) System.Threading.ExecutionContext:RunInternal(ExecutionContext, ContextCallback, Object, Boolean) System.Threading.ExecutionContext:Run(ExecutionContext, ContextCallback, Object, Boolean) System.Threading.Tasks.Task:ExecuteWithThreadLocal(Task&) System.Threading.Tasks.Task:ExecuteEntry(Boolean) System.Threading.Tasks.Task:System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() System.Threading.ThreadPoolWorkQueue:Dispatch() System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()(Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)
Using Facebook Unity SDK v8.1.1 with FBiOSSDK/8.2.0 UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption, String, Object) UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[]) UnityEngine.Logger:Log(LogType, Object) UnityEngine.Debug:Log(Object) Facebook.Unity.DebugLogger:Info(String) Facebook.Unity.FacebookLogger:Info(String) Facebook.Unity.FB:LogVersion() Facebook.Unity.CompiledFacebookLoader:Start()
And here, from the unity console once it is built in the iphone:
[NORMAL LOGIN BUTTON]
Autoconnected Player NullReferenceException: Object reference not set to an instance of an object. at AuthManager.Login (System.String _email, System.String _password) [0x00000] in <00000000000000000000000000000000>:0 at AuthManager.LoginButton () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.Events.UnityAction.Invoke () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.Events.InvokableCall.Invoke () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.Events.UnityEvent.Invoke () [0x00000] in <00000000000000000000000000000000>:0 at Lean.Gui.LeanButton.DoClick () [0x00000] in <00000000000000000000000000000000>:0 at Lean.Gui.LeanButton.OnPointerUp (UnityEngine.EventSystems.PointerEventData eventData) [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerUpHandler handler, UnityEngine.EventSystems.BaseEventData eventData) [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.EventSystems.ExecuteEvents+EventFunction
1[T1].Invoke (T1 handler, UnityEngine.EventSystems.BaseEventData eventData) [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction
1[T1] functor) [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.EventSystems.StandaloneInputModule.ProcessTouchPress (UnityEngine.EventSystems.PointerEventData pointerEvent, System.Boolean pressed, System.Boolean released) [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.EventSystems.StandaloneInputModule.ProcessTouchEvents () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.EventSystems.StandaloneInputModule.Process () [0x00000] in <00000000000000000000000000000000>:0 at UnityEngine.EventSystems.EventSystem.Update () [0x00000] in <00000000000000000000000000000000>:0 UnityEngine.DebugLogHandler:Internal_LogException(Exception, Object) UnityEngine.DebugLogHandler:LogException(Exception, Object) UnityEngine.Logger:LogException(Exception, Object) UnityEngine.Debug:LogException(Exception) UnityEngine.EventSystems.ExecuteEvents:Execute(GameObject, BaseEventData, EventFunction`1) UnityEngine.EventSystems.StandaloneInputModule:ProcessTouchPress(PointerEventData, Boolean, Boolean) UnityEngine.EventSystems.StandaloneInputModule:ProcessTouchEvents() UnityEngine.EventSystems.StandaloneInputModule:Process() UnityEngine.EventSystems.EventSystem:Update()(Filename: currently not available on il2cpp Line: -1)
[FACEBOOK LOGIN BUTTON]
Autoconnected Player NullReferenceException: Object reference not set to an instance of an object. at AuthManager.loginviaFirebaseFacebook (Facebook.Unity.AccessToken accessToken) [0x00000] in <00000000000000000000000000000000>:0 at FacebookInit.authStatusCallback (Facebook.Unity.ILoginResult result) [0x00000] in <00000000000000000000000000000000>:0 at Facebook.Unity.FacebookDelegate`1[T].Invoke (T result) [0x00000] in <00000000000000000000000000000000>:0 at Facebook.Unity.CallbackManager.TryCallCallback[T] (System.Object callback, Facebook.Unity.IResult result) [0x00000] in <00000000000000000000000000000000>:0 at Facebook.Unity.CallbackManager.CallCallback (System.Object callback, Facebook.Unity.IResult result) [0x00000] in <00000000000000000000000000000000>:0 at Facebook.Unity.CallbackManager.OnFacebookResponse (Facebook.Unity.IInternalResult result) [0x00000] in <00000000000000000000000000000000>:0 at Facebook.Unity.FacebookBase.OnAuthResponse (Facebook.Unity.LoginResult result) [0x00000] in <00000000000000000000000000000000>:0 at Facebook.Unity.Mobile.MobileFacebook.OnLoginComplete (Facebook.Unity.ResultContainer resultContainer) [0x00000] in <00000000000000000000000000000000>:0 at Facebook.Unity.FacebookGameObject.OnLoginComplete (System.String message) [0x00000] in <00000000000000000000000000000000>:0
(Filename: currently not available on il2cpp Line: -1)
**I am adding this bug report here because those problems did not start to happen until I added the FB SDK, and given that I have zero knowledge on the subject, I though it was ok to add it here and in the firebase forum.