【发布时间】:2020-08-18 02:24:51
【问题描述】:
在登录新用户或创建新用户时使用电子邮件有 2 种不同的方法签名。在创建新用户时,如果电子邮件已存在,则会返回错误;如果电子邮件不存在,则会返回错误:
// create account
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: { (authDataResult, error)
if let error = error {
// if this email address already exists an error will be returned
return
}
})
// login
Auth.auth().signIn(withEmail: emailTextField.text!, password: self.passwordTextField.text!, completion: { (authDataResult, error) in
if let error = error {
// if this email address isn't inside the system then an error will be returned
return
}
})
但是,当使用用户的电话号码登录或创建新帐户时,我必须在两种情况下使用相同的方法签名。
func loginExistingUserOrCreateNewOne(phoneNumber: String, verificationCode: String) {
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
if let error = error { return }
guard let verificationId = verificationID else { return }
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationId, verificationCode: verificationCode)
Auth.auth().signIn(with: credential, completion: { (authDataResult, error) in
guard let authUser = authDataResult else { return }
let checkUsersRef = Database.database().reference().child("users").child(authUser.user.uid)
checkExistingUsersRef.observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists() {
// this is a new user, now add them to the users ref
let newUserDict = ["signupDate": Date().timeIntervalSince1970]
checkUsersRef.updateChildValues(newUserDict, withCompletionBlock: { (error, ref) in
if let error = error {
// because there is an error this ref was never updated so now I have to sign this user out and they have to start over agin
do {
try Auth.auth().signOut()
} catch let err as NSError {
// alert user there is a major problem
}
return
}
// if no error let them go to HomeVC
})
return
}
// this is a previous user fetch dict data and let them proceed to HomeVC
guard let previousUserDict = snapshot.value as? [String: Any] else { return }
// get newUserDict values and let them go to HomeVC
})
})
}
}
如果用户已经有一个帐户,我需要从用户 ref 获取一些数据,然后让他们继续使用 HomeVC。如果用户之前从未注册过,那么我必须将它们添加到用户引用中,然后让他们继续。这是一个两步的过程。
问题是这些额外的步骤似乎是不必要的。例如,使用电子邮件签名或登录会返回错误,因此无需在另一个 ref 中创建和检查该电子邮件是否已存在。
除了在我上面的代码中使用这个过程之外,还有什么其他方法可以让我在创建新帐户之前确定电话号码是否存在,或者在登录时它是否不存在?
【问题讨论】:
标签: ios swift firebase firebase-realtime-database firebase-authentication