如何将Android项目SendOtpCodeAsync的verificationId传到共享项目按钮点击事件
实现步骤
1. 修改共享项目IAuth接口定义
原有接口仅返回布尔状态,调整为同时返回验证状态和verificationId,可直接用元组实现,如需扩展更多返回字段也可自定义结果类:
namespace TestApp_MiniApps.Views.Xamarin.FireBase { public interface IAuth { // 修改返回值为包含成功状态和verificationId的元组 Task<(bool IsSuccess, string VerificationId)> SendOtpCodeAsync(string phonenumber); } }
2. 修改Android项目AuthDriod实现
调整TaskCompletionSource的泛型类型,在回调中把verificationId带回共享项目:
[assembly: Dependency(typeof(AuthDriod))] namespace TestApp_MiniApps.Droid { public class AuthDriod : PhoneAuthProvider.OnVerificationStateChangedCallbacks, IAuth { // 泛型修改为和接口返回匹配的元组 private TaskCompletionSource<(bool IsSuccess, string VerificationId)> _phoneAuthTcs; public Task<(bool IsSuccess, string VerificationId)> SendOtpCodeAsync(string phonenumber) { _phoneAuthTcs = new TaskCompletionSource<(bool IsSuccess, string VerificationId)>(); Java.Lang.Long num = (Java.Lang.Long)60; PhoneAuthOptions options = PhoneAuthOptions.NewBuilder(FirebaseAuth.Instance) .SetPhoneNumber(phonenumber) .SetTimeout(num, TimeUnit.Seconds) .SetActivity(Platform.CurrentActivity) .SetCallbacks(this) .Build(); PhoneAuthProvider.VerifyPhoneNumber(options); return _phoneAuthTcs.Task; } public override void OnVerificationCompleted(PhoneAuthCredential credential) { // 自动验证成功场景可按需返回credential相关信息,此处按原有逻辑兼容 _phoneAuthTcs?.TrySetResult((true, string.Empty)); } public override void OnVerificationFailed(FirebaseException exception) { // 验证失败返回false和空id _phoneAuthTcs?.TrySetResult((false, string.Empty)); } public override void OnCodeSent(string verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken) { base.OnCodeSent(verificationId, forceResendingToken); // 把回调拿到的verificationId作为返回值传给共享项目 _phoneAuthTcs?.TrySetResult((true, verificationId)); } } }
3. 共享项目接收verificationId
将拿到的verificationId存为全局变量,后续提交验证码校验时使用即可:
// 页面全局变量,存储后续校验需要的verificationId private string _currentVerificationId; IAuth auth; auth = DependencyService.Get<IAuth>(); private async void SendCode_Button_Clicked(object sender, EventArgs e) { var result = await auth.SendOtpCodeAsync(PhonenumberEntry.Text); if (result.IsSuccess) { _currentVerificationId = result.VerificationId; // 此处执行跳转到验证码输入页、显示验证码输入框等逻辑 } else { // 此处执行验证码发送失败的提示逻辑 } }
如果你后续需要返回更多字段(比如错误信息、验证码重发token),可以自定义一个
SendOtpResult类替代元组,扩展性更好。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

