我正在使用云火力存储进行手机验证。在火力存储数据库中,我存储了用户的电话号码和UID。以下是我尝试用于手机号登录的代码:
@IBAction func signUp(_ sender: Any) {
// dismiss keyboard
view.endEditing(true)
if sendOTP == false {
let mobileNumber = "+91" + phoneNumberTextField.text!
self.Userdefaults.set(mobileNumber, forKey: "mobileNumber")
print("mobileNumber::::\(mobileNumber)")
sendOTPCode()
sendOTP = true
} else {
let codestring = OTPCodeTextField.text
if codestring?.count == 6 {
loginusingOTP(OTPtext: codestring!)
} else {
print("Enter 6 digit code")
}
}
func sendOTPCode() {
let mymobilenumber = Userdefaults.string(forKey: "mobileNumber")
PhoneAuthProvider.provider().verifyPhoneNumber(mymobilenumber!) { (verificationID, error) in
self.Userdefaults.set(verificationID, forKey: "authVerificationID")
if error != nil
{
print ("insde SendCode, there is error")
print("error: \(String(describing: error?.localizedDescription))")
} else {
print ("code sent")
self.phoneNumberTextField.allowsEditingTextAttributes = false
}
}
}
func loginusingOTP(OTPtext: String) {
let db = Firestore.firestore()
let verificationID = self.Userdefaults.string(forKey: "authVerificationID")
let credential: PhoneAuthCredential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID!,
verificationCode: OTPtext)
Auth.auth().signIn(with: credential)
{
(user, error) in
if error != nil
{
print("error: \(String(describing: error?.localizedDescription))")
}
else if user != nil
{
print("Phone number: \(String(describing: user?.phoneNumber))")
let userInfo = user?.providerData[0]
print("Provider ID: \(String(describing: userInfo?.providerID))")
var _: DocumentReference? = nil
print("currentUser:::\(String(describing: currentUser))")
db.collection("users").document(currentUser!).setData([
"User_Phone_number": user?.phoneNumber as Any,
"uid": currentUser as Any
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
if PrefsManager.sharedinstance.isFirstTime == false{
let when = DispatchTime.now() + 0
DispatchQueue.main.asyncAfter(deadline: when) {
self.performSegue(withIdentifier: "signUpToTabBar", sender: nil)
}
}else{
let when = DispatchTime.now() + 0
DispatchQueue.main.asyncAfter(deadline: when) {
let storyboard = UIStoryboard(name: "Start", bundle: nil)
let initialViewController = storyboard.instantiateViewController(withIdentifier: "onboardvc")
self.present(initialViewController, animated: true, completion: nil)
}
}
}
}
} else {
print("error::::::")
}
}
}
用户登录流程 - 首先用户输入手机号码,然后点击发送OTP,然后用户输入OTP代码,成功登录。由于用户第一次登录,需要填写用户详细信息页面,然后进入首页。如果已经登录的用户,在成功登录后将被重定向到主屏幕而不是用户详细页面。
我的问题是现在用户每次都要登录才能进入应用程序,我想让用户自动登录,除非用户注销。如何检查云Firestore中已登录用户的UID或电话是否存在或为新用户。
任何帮助都非常感谢...
UserDefaults
中设置标志。每次需要检查标志是否为真,然后重定向到主屏幕(您需要在didFinishLaunchingWithOptions
中编写代码)。否则,默认的登录屏幕将打开。在注销时,您需要从UserDefaults
中删除此标志值。 - AbecedarioPoint