如何在 Kotlin 中使用 Firebase 实现 phone 身份验证?

How to implement phone Authentication using Firebase in Kotlin?

我正在使用 Firebase Phone 身份验证开发 Kotlin 应用程序。我对实施此验证电话号码感到困惑。

private fun startPhoneNumberVerification(phoneNumber: String, mCallbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks?) {
    Log.d("phoneNumber==", "" + phoneNumber);
    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this@LoginActivity,               // Activity (for callback binding)
            mCallbacks)
}

执行上面的代码并得到错误("None of the following functions can be called with the aruguments supplied")和 "creating extension function PhoneAuthProvider?.verifyPhoneNumber"。有人可以指导我吗?

我想不出其他任何东西,所以我假设 Firebase 回调参数被注释为非空。

TL;DR:从回调参数中删除 ? 或当它为 null 时不执行任何操作,以便 Kotlin 可以进行一些神奇的类型推断。

class MainActivity : AppCompatActivity() {

    var fbAuth = FirebaseAuth.getInstance()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var btnLogin = findViewById<Button>(R.id.btnLogin)
        btnLogin.setOnClickListener {view ->
            signIn(view,"user@company.com", "pass")
        }
    }

    fun signIn(view: View,email: String, password: String){
        showMessage(view,"Authenticating...")

        fbAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, OnCompleteListener<AuthResult> { task ->
            if(task.isSuccessful){
                var intent = Intent(this, LoggedInActivity::class.java)
                intent.putExtra("id", fbAuth.currentUser?.email)
                startActivity(intent)

            }else{
                showMessage(view,"Error: ${task.exception?.message}")
            }
        })

    }

    fun showMessage(view:View, message: String){
        Snackbar.make(view, message, Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show()
    }

}

由于您确定回调不会为空,因为您将在 onCreate 中对其进行初始化,因此将其声明为

    lateinit var mCallbacks: PhoneAuthProvider.OnVerificationStateChangedCallbacks

这对我有用