Android 将Firebase电话身份验证与协同程序一起使用
我想使用Firebase电话身份验证在我的应用程序中创建签名活动。身份验证分为三个阶段:Android 将Firebase电话身份验证与协同程序一起使用,android,firebase,kotlin,firebase-authentication,kotlin-coroutines,Android,Firebase,Kotlin,Firebase Authentication,Kotlin Coroutines,我想使用Firebase电话身份验证在我的应用程序中创建签名活动。身份验证分为三个阶段: 使用PhoneAuthProvider发送验证码。verifyPhoneNumber(选项) 使用PhoneAuthProvider.getCredential(verificationId!!,code) 使用auth.signwithcredential(凭证)登录用户 我想使用协程来处理签名过程。我知道如何使用await()处理代码验证,它将auth.signInWithCredential(cred
PhoneAuthProvider发送验证码。verifyPhoneNumber(选项)
PhoneAuthProvider.getCredential(verificationId!!,code)
auth.signwithcredential(凭证)登录用户
await()
处理代码验证,它将auth.signInWithCredential(credential)
返回的任务包装起来
我的问题是PhoneAuthProvider.verifyPhoneNumber(选项)
函数,它是一个void
函数。我必须使用回调来处理此方法
val options = PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setCallbacks(callback)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
其中回调
为:
callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks(){
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
Timber.i("onVerificationCompleted:$credential")
signInWithPhoneAuthCredential(credential)
}
override fun onVerificationFailed(e: FirebaseException) {
Timber.i(e,"onVerificationFailed")
}
override fun onCodeSent(verificationId: String, token: PhoneAuthProvider.ForceResendingToken) {
Timber.i("onCodeSent:$verificationId")
storedVerificationId = verificationId
resendToken = token
}
}
问题是:有没有办法将await()
与verifyPhoneNumber
函数一起使用?
否则,如何使用带回调的协程来阻止函数,直到触发回调为止?您可以使用将Firebase回调包装到协程挂起函数中,如下所示:
sealed class PhoneAuthResult {
data class VerificationCompleted(val credentials: PhoneAuthCredential) : PhoneAuthResult()
data class CodeSent(val verificationId: String, val token: PhoneAuthProvider.ForceResendingToken)
: PhoneAuthResult()
}
private suspend fun performPhoneAuth(
phoneNumber: String,
firebaseAuth: FirebaseAuth): PhoneAuthResult =
suspendCoroutine { cont ->
val callback = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
Timber.i("onVerificationCompleted:$credential")
cont.resume(
PhoneAuthResult.VerificationCompleted(credential)
)
}
override fun onVerificationFailed(e: FirebaseException) {
Timber.i(e, "onVerificationFailed")
cont.resumeWithException(e)
}
override fun onCodeSent(verificationId: String, token: PhoneAuthProvider.ForceResendingToken) {
Timber.i("onCodeSent:$verificationId")
cont.resume(
PhoneAuthResult.CodeSent(verificationId, token)
)
}
}
val options = PhoneAuthOptions.newBuilder(firebaseAuth)
.setPhoneNumber(phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setCallbacks(callback)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
callbacks
不是已经在做你想做的事情了吗?@NaveenNiraula但是callbacks是不可阻止的,我的viewmodel必须观察函数的结果为什么你不把你的代码放在onVerificationCompleted(){}
中,或者我没有得到你想要做的事情?@NaveenNiraula是的,我可以做到,但是另一个函数verifyPhoneNumber
将在调用之前完成