Firebase电话认证在Xamarin中出错

q3aa0525  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(172)

我正在Xamarin中测试Firebase电话验证。以下是我采取的步骤:
1.添加NuGet包:Xamarin.Firebase.授权,Xamarin.Firebase.安卓项目的核心.
1.要启动电话号码验证:

  • 添加类:帐户服务授权电话.cs
[assembly: Dependency(typeof(AccountServiceAuthPhone))]
namespace XXXXX.Droid
{
  public class AccountServiceAuthPhone : PhoneAuthProvider.OnVerificationStateChangedCallbacks, IAccountService
  {
      public AccountServiceAuthPhone()
      {
      }

      //const int OTP_TIMEOUT = 30; // seconds
      private string _verificationId;
      private FirebaseAuth mAuth;
      private PhoneAuthProvider.ForceResendingToken mResendToken;
      private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;

      public override void OnVerificationCompleted(PhoneAuthCredential credential)
      {
          System.Diagnostics.Debug.WriteLine("PhoneAuthCredential created Automatically");
      }

      public override void OnVerificationFailed(FirebaseException exception)
      {
          System.Diagnostics.Debug.WriteLine("Verification Failed: " + exception.Message);
      }

      public override void OnCodeSent(string verificationId, PhoneAuthProvider.ForceResendingToken forceResendingToken)
      {
          base.OnCodeSent(verificationId, forceResendingToken);
          _verificationId = verificationId;
      }
      public Task<bool> SendOtpCodeAsync(string phoneNumber)
      {
          PhoneAuthOptions options =
          PhoneAuthOptions.NewBuilder(mAuth)
                  .SetPhoneNumber(phoneNumber)       // Phone number to verify
                  .SetTimeout((Java.Lang.Long)60L, TimeUnit.Seconds) // Timeout and unit
                  .SetActivity(Platform.CurrentActivity)              // Activity (for callback binding)
                  .SetCallbacks(mCallbacks)   // OnVerificationStateChangedCallbacks
                  .Build();
          PhoneAuthProvider.VerifyPhoneNumber(options);
          return Task.FromResult(true);
      }

      private void OnAuthCompleted(Task task, TaskCompletionSource<bool> tcs)
      {
          if (task.IsCanceled || task.IsFaulted)
          {
              // something went wrong
              tcs.SetResult(false);
              return;
          }
          _verificationId = null;
          tcs.SetResult(true);
      }

      public Task<bool> VerifyOtpCodeAsync(string code)
      {
          if (!string.IsNullOrWhiteSpace(_verificationId))
          {
              var credential = PhoneAuthProvider.GetCredential(_verificationId, code);
              var tcs = new TaskCompletionSource<bool>();
              FirebaseAuth.Instance.SignInWithCredentialAsync(credential)
                  .ContinueWith((task) => OnAuthCompleted(task, tcs));
              return tcs.Task;
          }
          return Task.FromResult(false);
      }
  }
}
  • 添加接口IAccountService.cs
public interface IAccountService
{        
    Task<bool> SendOtpCodeAsync(string phoneNumber);
    Task<bool> VerifyOtpCodeAsync(string code);
}
  • Login.xaml.cs
private async void _nextlogin_Tapped(object sender, EventArgs e)
{
    if (txt_phone.Text != null && !string.IsNullOrWhiteSpace(txt_phone.Text.Trim().Replace("'", "").Replace("&", "")))
    {
      string phone = txt_phone.Text;

      await _accountService.SendOtpCodeAsync(phone);

      Preferences.Set("PhoneGetOTP", txt_phone.Text);
      await Navigation.PushAsync(new ConfirmOTP());
    }         
}

1.去谷歌云控制台,选择你的项目。
1.单击导航菜单并选择API &服务,然后选择 Jmeter 板。
1.点击启用API和服务,启用API“Android设备验证”。
1.添加SHA-1并下载,替换项目中最新的google-services.json文件。

但是,当我调试时,它给出了一个错误:“未将对象引用设置为对象”的示例。看起来它未执行到:public Task<bool> SendOtpCodeAsync(string phoneNumber).期待大家的帮助。谢谢

ej83mcc0

ej83mcc01#

我建议您对SendOtpCodeAsync使用此方法:

private TaskCompletionSource<bool> _phoneAuthTcs;

    public Task<bool> SendOtpCodeAsync(string phoneNumber)
    {
        if (string.IsNullOrWhiteSpace(phoneNumber))
        {
            return Task.FromResult(false);
        }

        try
        {
            _phoneAuthTcs = new TaskCompletionSource<bool>();

            FirebaseAuth auth = FirebaseAuth.Instance;

            PhoneAuthOptions options = PhoneAuthOptions.NewBuilder(auth)
            .SetPhoneNumber(phoneNumber)       // Phone number to verify
            .SetTimeout((Java.Lang.Long)120L, TimeUnit.Seconds) // Timeout and unit
            .SetActivity(Platform.CurrentActivity)                 // Activity (for callback binding)
            .SetCallbacks(this)          // OnVerificationStateChangedCallbacks
            .Build();

            PhoneAuthProvider.VerifyPhoneNumber(options);

            return Task.FromResult(true);// _phoneAuthTcs.Task; //Task.FromResult(true);//
        }
        catch (Exception Ex)
        {
            Console.WriteLine("Firebase Phoneauth Exception:" + Ex.Message + "//////");
            return null;
        }
    }

这对我很有效。代码取自:Xamarin.Andorid Firebase Phone Auth, SMS OTP Send , User Add

相关问题