从Firebase Firestore获取当前用户的价值-Swift 4

时间:2019-03-24 22:59:34

标签: swift firebase google-cloud-firestore

这是我在这里的第一个问题,希望您能帮助我。

我一直在尝试为登录我的应用程序的当前用户获取特定路径。

我现在真的不是我做错了什么,所以我将代码粘贴到这里。

func userRoleListener() {

guard let user = Auth.auth().currentUser else { return } . 
Firestore.firestore().collection("users").document("sjbD5SvKTYHWBLhCqojs").getDocument { (snapshot, error) in
 if let data = snapshot?.data() {
 guard let isAdmin = data["isAdmin"] as? Bool else { return }
   if isAdmin {
    self.applyButton.isHidden = true
   } else {
     self.applyButton.isHidden = false
   }
  }
 }
}

这是我创建用户的功能。

private func createUser() {

        guard let nameAndLastname = nameAndLastnameTextField.text , let email = emailTextField.text , let password = passwordTextField.text , !nameAndLastname.isEmpty , !email.isEmpty , !password.isEmpty else {
            simpleAlert(title: "Error", msg: "Debe completar todos los campos")
            return

        }

        let newUserReference = Firestore.firestore().collection("users").document()

        newUserReference.setData([
            "nameAndLastname": nameAndLastname,
            "email": email,
            "password": password,
            "isAdmin": false,
            "timestamp": Timestamp()
            ])
    }

这是我的登录操作:

@IBAction func signUpButtonPressed(_ sender: Any) {

        guard let email = emailTextField.text , let password = passwordTextField.text , !email.isEmpty , !password.isEmpty else { return }

        self.signUpButton.animateButton(shouldLoad: true, withMessage: "")

        Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
            if let error = error {
                self.signUpButton.animateButton(shouldLoad: false, withMessage: "¡REGISTRAR!")
                debugPrint(error.localizedDescription)
                self.simpleAlert(title: "Error", msg: "Error al iniciar sesión, intente nuevamente en unos minutos")
                return
            }

            self.signUpButton.animateButton(shouldLoad: false, withMessage: "")
            self.createUser()
            self.presentClientStoryboard()

        }

    }

这是我的数据库的图像:

Database image

2 个答案:

答案 0 :(得分:1)

如果您使用Firebase身份验证创建用户,则身份验证将在Firebase身份验证(非Firestore)中为您创建一个用户和一个用户ID

因此,当您在Firestore中创建用户时,必须将userID设置为文档ID,如下所示:

@IBAction func signUpButtonPressed(_ sender: Any) {

    guard let email = emailTextField.text , let password = passwordTextField.text , !email.isEmpty , !password.isEmpty else { return }

    self.signUpButton.animateButton(shouldLoad: true, withMessage: "")

    Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
        if let error = error {
            self.signUpButton.animateButton(shouldLoad: false, withMessage: "¡REGISTRAR!")
            debugPrint(error.localizedDescription)
            self.simpleAlert(title: "Error", msg: "Error al iniciar sesión, intente nuevamente en unos minutos")
            return
        }

        self.signUpButton.animateButton(shouldLoad: false, withMessage: "")
        self.createUser(user.uid)       // <----- user id from Firebase Auth
        self.presentClientStoryboard()

    }

}

private func createUser(userId: String) {

    guard let nameAndLastname = nameAndLastnameTextField.text , let email = emailTextField.text , let password = passwordTextField.text , !nameAndLastname.isEmpty , !email.isEmpty , !password.isEmpty else {
        simpleAlert(title: "Error", msg: "Debe completar todos los campos")
        return

    }

    let newUserReference = Firestore.firestore().collection("users").document(userId)    // <-- create a document, with the user id from Firebase Auth

    newUserReference.setData([
        "nameAndLastname": nameAndLastname,
        "email": email,
        "password": password,
        "isAdmin": false,
        "timestamp": Timestamp()
        ])
}

答案 1 :(得分:0)

您应该从当前用户那里获取用户ID,请尝试以下操作:

func userRoleListener() {

guard let userUid = Auth.auth().currentUser.uid else { return } . 
Firestore.firestore().collection("users").document(userUid).getDocument { (snapshot, error) in
 if let data = snapshot?.data() {
 guard let isAdmin = data["isAdmin"] as? Bool else { return }
   if isAdmin {
// And I believe here the true and false values should be switched as you are checking if the user IS an admin, if they are an admin, shouldn't you show the button?
    self.applyButton.isHidden = false
   } else {
     self.applyButton.isHidden = true
   }
  }
 }
}

这是当前用户登录到应用程序,然后使用用户uid来搜索数据库。只要确保在创建帐户时就保存了相应的用户数据即可。