首页 > 解决方案 > 适用于 Xamarin 表单的 Xamarin Firebase PhoneAuth

问题描述

我需要创建一个具有 Firebase 电话身份验证的 Xamarin Forms 应用程序。有一个用于 Xamarin Firebase 身份验证的包,带有电话身份验证,但没有 Xamarin Forms 的文档。

到目前为止,对于 Android,我有:

public class FirebaseAuthenticator : IFirebaseAuthenticator
    {
        public async Task<string> RegisterWithPhoneNumber(string number)
        {
            PhoneAuthCallbacks phoneAuthCallbacks = new PhoneAuthCallbacks();
            var user = await PhoneAuthProvider.Instance.VerifyPhoneNumber(number, 60, TimeUnit.Seconds, this, phoneAuthCallbacks);
            return user;
        }
    }

我的 PhoneAuthCallbacks 类:

public class PhoneAuthCallbacks : PhoneAuthProvider.OnVerificationStateChangedCallbacks
    {
        public override void OnVerificationCompleted(PhoneAuthCredential credential)
        {
            // This callback will be invoked in two situations:
            // 1 - Instant verification. In some cases the phone number can be instantly
            //     verified without needing to send or enter a verification code.
            // 2 - Auto-retrieval. On some devices Google Play services can automatically
            //     detect the incoming verification SMS and perform verification without
            //     user action.        
            FirebaseAuth.Instance.SignInWithCredential(credential);
            System.Diagnostics.Debug.WriteLine("onVerificationCompleted");
        }

        public override void OnVerificationFailed(FirebaseException exception)
        {
            // This callback is invoked in an invalid request for verification is made,
            // for instance if the the phone number format is not valid.
            System.Diagnostics.Debug.WriteLine("onVerificationFailed: " + exception);
        }

        public override void OnCodeSent(string verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken)
        {
            // The SMS verification code has been sent to the provided phone number, we
            // now need to ask the user to enter the code and then construct a credential
            // by combining the code with a verification ID.
            base.OnCodeSent(verificationId, forceResendingToken);
            System.Diagnostics.Debug.WriteLine("onCodeSent" + verificationId);
        }
    }

但它不起作用。在 RegisterWithPhoneNumber 中,'this' 给出错误“无法从 xx.Droid.FirebaseAuthenticator 转换为 Android.App.Activity”

标签: androidfirebasexamarinxamarin.formsfirebase-authentication

解决方案


要添加到上一个答案,如果您使用的是 Xamarin Essentials,您可以使用它Platform.CurrentActivity来获取 MainActivity 的实例。


推荐阅读