Phone 在 ios swift 中使用云 Firestore 进行身份验证?

Phone authentication using cloud firestore in ios swift?

在我的应用程序中,我使用 phone 身份验证进行登录,并在数据库中存储用户登录用户 phone 号码和 uid。当使用现有用户 phone 号码登录时,它会创建具有相同 uid 和 phone 号码的新文档 ID,您可以查看图像 1 和 3。

这是我用来登录的代码,如果用户存在意味着它应该检查并导航到主控制器,否则请登录用户详细信息控制器。

     @IBAction func loginbtn(_ sender: UIButton) {

    let defaults = UserDefaults.standard
    let credential: PhoneAuthCredential = PhoneAuthProvider.provider().credential(withVerificationID: defaults.string(forKey: "authVID")!,
                                                                                  verificationCode: otpText.text!)
    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))")

            let currentUser = Auth.auth().currentUser?.uid
            var ref: DocumentReference? = nil


            ref = self.db.collection("Users").addDocument(data: [
                                    "phoneNumber"   : user?.phoneNumber as Any,
                                    "UID"           : user?.uid as Any

                                ]) { err in
                                    if let err = err {

                                        print("Error adding document: \(err)")

                                    } else {

                                        print("Document added with ID: \(ref!.documentID)")

                                    }
                                }

            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "HomeViewController")
            self.present(controller, animated: true, completion: nil)


        } else {




            }


        }

    }

谁能帮我解决这个问题,过去的一天我几乎都在挣扎!!!

您正在调用函数 "add",该函数创建一个新文档并分配一个自动生成的 ID,如 here 所述。 相反,您需要使用用户的 uid 作为键来调用函数 "set",如下所示:

db.collection("users").doc(uid).set... 

您也可以使用 firebase 生成的 UID。 您已经拥有该行,但尚未使用它:

let currentUser = Auth.auth().currentUser?.uid

所以尝试用"UID": currentUser as Any

替换"UID": user?.uid as Any