You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建非Xamarin.Forms独立iOS/Android项目,集成Firebase PhoneAuth遇阻

我之前也碰到过类似的情况,原生Xamarin项目集成Firebase PhoneAuth确实比Forms麻烦点,而且官方文档这块确实有点缺失。下面给你分步说下iOS和Android各自的实现方式,都是基于Xamarin.Firebase.Auth库的:

Android 端实现步骤
  • 第一步:配置Firebase项目
    先在Firebase控制台完成Android应用的注册,下载google-services.json文件放到Android项目根目录,右键文件设置生成操作为GoogleServicesJson。

  • 第二步:初始化Firebase Auth
    在MainActivity的OnCreate方法里先初始化Firebase,再获取Auth实例:

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        // 初始化Firebase
        FirebaseApp.InitializeApp(this);
        // 获取Auth实例
        var auth = FirebaseAuth.Instance;
    }
    
  • 第三步:发送验证码
    通过PhoneAuthProvider创建回调处理类,调用VerifyPhoneNumber发送验证码:

    private string _verificationId;
    private PhoneAuthProvider.ForceResendingToken _resendToken;
    
    private void SendVerificationCode(string phoneNumber)
    {
        var callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks(
            verificationCompleted: credential => 
            {
                // 自动验证完成,直接登录
                auth.SignInWithCredentialAsync(credential).ContinueWith(task => 
                {
                    if (task.IsCompletedSuccessfully)
                    {
                        // 处理登录成功逻辑
                        var user = task.Result.User;
                    }
                });
            },
            verificationFailed: exception => 
            {
                // 验证失败,打印错误信息
                Console.WriteLine($"验证失败:{exception.Message}");
            },
            codeSent: (verificationId, forceResendingToken) => 
            {
                // 保存验证ID和重发令牌,用于后续验证或重发
                _verificationId = verificationId;
                _resendToken = forceResendingToken;
                // 这里可以跳转到验证码输入页面
            },
            codeAutoRetrievalTimeOut: verificationId => 
            {
                // 验证码自动获取超时,提示用户手动输入
            }
        );
    
        PhoneAuthProvider.Instance.VerifyPhoneNumber(
            phoneNumber: phoneNumber, // 必须带国家码,比如"+86138xxxxxxx"
            timeout: 60,
            unit: TimeUnit.Seconds,
            activity: this,
            callbacks: callbacks);
    }
    
  • 第四步:验证用户输入的验证码
    获取用户输入的验证码后,创建凭证并完成登录:

    private async Task VerifyCode(string userInputCode)
    {
        var credential = PhoneAuthProvider.GetCredential(_verificationId, userInputCode);
        try
        {
            var result = await auth.SignInWithCredentialAsync(credential);
            var currentUser = result.User;
            // 登录成功,处理用户信息
        }
        catch (FirebaseAuthException ex)
        {
            // 验证码错误或其他登录异常
            Console.WriteLine($"登录失败:{ex.Message}");
        }
    }
    
iOS 端实现步骤
  • 第一步:配置Firebase项目
    在Firebase控制台注册iOS应用,下载GoogleService-Info.plist放到iOS项目根目录,设置生成操作为BundleResource。

  • 第二步:初始化Firebase
    在AppDelegate的FinishedLaunching方法里初始化Firebase:

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        Firebase.Core.App.Configure();
        // 其他初始化逻辑
        return true;
    }
    
  • 第三步:自定义PhoneAuth委托类
    iOS的PhoneAuth回调需要通过自定义委托类实现,先创建一个继承自PhoneAuthProviderDelegate的类:

    public class CustomPhoneAuthDelegate : PhoneAuthProviderDelegate
    {
        public Action<PhoneAuthCredential> OnVerificationCompleted { get; set; }
        public Action<NSError> OnVerificationFailed { get; set; }
        public Action<string, PhoneAuthProviderForceResendingToken> OnCodeSent { get; set; }
        public Action<string> OnCodeAutoRetrievalTimeout { get; set; }
    
        public override void VerificationCompleted(PhoneAuthProvider provider, PhoneAuthCredential credential)
        {
            OnVerificationCompleted?.Invoke(credential);
        }
    
        public override void VerificationFailed(PhoneAuthProvider provider, NSError error)
        {
            OnVerificationFailed?.Invoke(error);
        }
    
        public override void CodeSent(PhoneAuthProvider provider, string verificationID, PhoneAuthProviderForceResendingToken forceResendingToken)
        {
            OnCodeSent?.Invoke(verificationID, forceResendingToken);
        }
    
        public override void CodeAutoRetrievalTimeOut(PhoneAuthProvider provider, string verificationID)
        {
            OnCodeAutoRetrievalTimeout?.Invoke(verificationID);
        }
    }
    
  • 第四步:发送验证码
    实例化自定义委托,调用VerifyPhoneNumber发送验证码:

    private string _verificationId;
    private PhoneAuthProviderForceResendingToken _resendToken;
    
    private void SendVerificationCode(string phoneNumber)
    {
        var auth = Firebase.Auth.Auth.DefaultInstance;
        var provider = PhoneAuthProvider.DefaultProvider;
        var authDelegate = new CustomPhoneAuthDelegate();
    
        authDelegate.OnVerificationCompleted = credential => 
        {
            auth.SignInWithCredentialAsync(credential).ContinueWith(task => 
            {
                if (task.IsCompletedSuccessfully)
                {
                    var user = task.Result.User;
                    // 处理自动登录成功逻辑
                }
            });
        };
    
        authDelegate.OnVerificationFailed = error => 
        {
            Console.WriteLine($"验证失败:{error.LocalizedDescription}");
        };
    
        authDelegate.OnCodeSent = (verificationId, token) => 
        {
            _verificationId = verificationId;
            _resendToken = token;
            // 跳转到验证码输入页面
        };
    
        provider.VerifyPhoneNumber(
            phoneNumber: phoneNumber,
            timeout: 60,
            forceResendingToken: null,
            verificationDelegate: authDelegate,
            uiDelegate: null);
    }
    
  • 第五步:验证验证码
    同样通过凭证完成登录:

    private async Task VerifyCode(string userInputCode)
    {
        var auth = Firebase.Auth.Auth.DefaultInstance;
        var credential = PhoneAuthProvider.DefaultProvider.GetCredential(_verificationId, userInputCode);
        try
        {
            var result = await auth.SignInWithCredentialAsync(credential);
            var currentUser = result.User;
            // 登录成功逻辑
        }
        catch (NSErrorException ex)
        {
            Console.WriteLine($"登录失败:{ex.Error.LocalizedDescription}");
        }
    }
    
注意事项
  • 确保两个项目都安装了最新稳定版的Xamarin.Firebase.Auth NuGet包,版本尽量保持一致。
  • Android项目需要在AndroidManifest.xml中添加INTERNET权限,如果需要自动读取验证码,还需添加READ_SMS和RECEIVE_SMS权限。
  • iOS项目要在Info.plist中添加NSPhoneNumberUsageDescription(可选,但避免审核问题),且Bundle ID必须和Firebase控制台注册的一致。
  • 测试建议用真实设备,部分模拟器可能无法接收短信验证码(iOS模拟器支持Firebase测试号码,Android模拟器部分型号可用)。

内容的提问来源于stack exchange,提问作者Gino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:14:49