В настоящее время я работаю над реализацией Apple Sign In в своем проекте Unity с использованием Firebase, но столкнулся с некоторыми проблемами. Когда я нажимаю кнопку входа, появляется всплывающее окно Apple Sign In, и кажется, что процесс входа завершается успешно. Однако результаты аутентификации не отражаются в моей игре, и я не могу продолжить.
Вот соответствующая часть моего сценария диспетчера входа:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Firebase;
using Firebase.Auth;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
#if UNITY_IOS
using AppleAuth;
using AppleAuth.Enums;
using AppleAuth.Interfaces;
using AppleAuth.Native;
#endif
public class AppleSigninManager : MonoBehaviour
{
[SerializeField] GameObject kidsDetailPanel;
[SerializeField] GameObject RegisterPanel;
[SerializeField] DataLoadingScript loadData;
public TextMeshProUGUI infoText;
private FirebaseAuth auth;
private string rawNonce; // Declare rawNonce
private void Awake()
{
CheckFirebaseDependencies();
}
private void CheckFirebaseDependencies()
{
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
if (task.IsCompleted)
{
if (task.Result == DependencyStatus.Available)
auth = FirebaseAuth.DefaultInstance;
else
AddToInformation("Could not resolve all Firebase dependencies: " + task.Result.ToString());
}
else
{
AddToInformation("Dependency check was not completed. Error : " + task.Exception.Message);
}
});
}
public void SignInWithApple()
{
Debug.Log("Sign In With Apple");
#if UNITY_IOS
// Generate a rawNonce
rawNonce = GenerateNonce();
var appleAuthManager = new AppleAuthManager(new PayloadDeserializer());
appleAuthManager.LoginWithAppleId(
LoginOptions.IncludeEmail | LoginOptions.IncludeFullName,
credential =>
{
if (credential is IAppleIDCredential appleIdCredential)
{
var identityToken = System.Text.Encoding.UTF8.GetString(appleIdCredential.IdentityToken);
Debug.LogError("Got Id token: " + identityToken);
SignInWithAppleOnFirebase(identityToken);
}
},
error =>
{
AddToInformation("Apple Sign-In Failed: " + error.ToString());
});
#else
AddToInformation("Apple Sign-In is only supported on iOS.");
#endif
}
private void SignInWithAppleOnFirebase(string appleIdToken)
{
Firebase.Auth.Credential credential =
Firebase.Auth.OAuthProvider.GetCredential("apple.com", appleIdToken, rawNonce, null);
auth.SignInAndRetrieveDataWithCredentialAsync(credential).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInAndRetrieveDataWithCredentialAsync was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInAndRetrieveDataWithCredentialAsync encountered an error: " + task.Exception);
return;
}
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
FirebaseUser newUser = task.Result.User;
DataSaver.instance.SaveUserId(newUser.UserId);
loadData.LoadData(newUser.UserId);
Debug.LogFormat("User signed in successfully: {0} ({1})", newUser.DisplayName, newUser.UserId);
DataSaver.instance.dts.parentName = newUser.DisplayName;
DataSaver.instance.dts.mobileNumber = newUser.PhoneNumber;
DataSaver.instance.dts.email = newUser.Email;
});
}
private string GenerateNonce()
{
var nonce = new byte[32];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(nonce);
}
return Convert.ToBase64String(nonce);
}
IEnumerator Checking(string userId)
{
PlayerPrefs.SetString("login_ids", userId);
yield return StartCoroutine(DataSaver.instance.LoadDataEnum());
if (string.IsNullOrEmpty(DataSaver.instance.dts.childName))
{
DataSaver.instance.SaveUserId(userId);
CompleteProfile();
print("no data found");
}
else
{
SceneManager.LoadScene("UserProfile");
}
}
void CompleteProfile()
{
kidsDetailPanel.SetActive(true);
RegisterPanel.SetActive(false);
}
private void AddToInformation(string str) { infoText.text += "\n" + str; }
}
Шаги, которые я предпринял:
Настроил аутентификацию Firebase в консоли Firebase.
Настроил вход Apple в консоль Firebase.
Добавил необходимое разрешения и полномочия для входа в Apple в Xcode.
Вызвала функцию входа в Unity и проверила успешность.
Фактическое поведение:
Всплывающее окно входа в систему появляется и вроде завершается, но обновлений и изменений в игре нет. Я не получаю никаких ошибок в консоли xcode.
Дополнительная информация:
Версия Unity: 2023.2
Версия Firebase SDK: 11.9.0
Платформа : iOS
Если кто-то сталкивался с подобной проблемой или имеет предложения по ее устранению, буду очень признателен за вашу помощь!
Спасибо!
Я ожидаю, что после успешного входа в систему данные пользователя будут отражены в моей игре, и пользователь должен перейти на страницу своего профиля.
Здесь я добавляю XCode log при попытке отправить аутентификацию:
Using Auth Prod for testing
Unloading 219 unused Assets to reduce memory usage. Loaded
Objects now: 5262.
Total: 26.103375 ms (FindLiveObjects: 0.207583 ms
CreateObjectMapping: 0.088125 ms MarkObjects: 2.566959 ms
DeleteObjects: 23.240708 ms)
Using Auth Prod for testing.
UnityEngine.DebugLogHandler:Internal_Log(LogType, LogOption,
String, Object)
Firebase.AppUtil:PollCallbacks()
Firebase.Platform.FirebaseHandler:Update()
Using Sign in with Apple Unity Plugin - v1.4.3
-> applicationWillResignActive()
9.6.0 - [FirebaseAnalytics][I-ACS800014] Cannot get flag for
unregistered flag. SDK name, flag name: app_measurement,
session_stitching_token_feature_enabled
9.6.0 - [FirebaseAnalytics][I-ACS800014] Cannot get flag for
unregistered flag. SDK name, flag name: app_measurement,
session_stitching_token_feature_enabled
-> applicationDidBecomeActive()
Подробнее здесь: https://stackoverflow.com/questions/790 ... e-in-unity
Проблема со входом в Apple с использованием Firebase в Unity ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение