从Firebase数据库检索用户数据并显示在用户个人资料文本字段中

时间:2019-06-27 05:01:42

标签: ios swift database firebase

我想从Firebase数据库中检索用户数据(例如用户名,电子邮件,年龄,性别,身高等数据)并将其显示在UserProfileViewController中的文本字段中。用户注册并创建配置文件后,我已经能够成功将用户数据存储在数据库中。但是,我在从数据库取回数据并将其显示在用户个人资料视图控制器中时遇到了麻烦。我如何在ageTextField中显示用户年龄,在sexTextField中显示用户性别,等等?

我试图在CreateProfileViewController中为值(用户名,电子邮件,年龄,性别,身高等)创建字典,但是当我尝试在UserProfileViewController中检索它们时,它似乎不起作用。我想知道是否有人可以帮助我解决这个问题?

这是我的CreateProfileViewController的一部分,它将用户数据存储到数据库中:


//reference database
var ref : DatabaseReference!
ref = Database.database().reference().child("users")

 func profile(){

//get data from the current user who signed up (their uid and email), so that the profile data can be stored under the same user) 

        let key = ref.childByAutoId().key 
        let email = Auth.auth().currentUser?.email 


let user = [
                    "id": key,
                    "email": email,
                    "age": ageTextField.text! as String,
                    "gender": genderTextField.text! as String,
            "weight": weightTextField.text! as String,
            "height": heightTextField.text! as String,
            "monthlyGoal": monthlyGoalTextField.text! as String
        ]

self.ref.child(key).setValue(user)

}

 @IBAction func submitProfile(_ sender: Any) {
        profile()
        self.performSegue(withIdentifier: "toSegue", sender: self)
        print("User profile created!")//this takes them to the home page view controller once they successfully sign up and create a profile.

    }

1 个答案:

答案 0 :(得分:1)

使用uid作为存储用户详细信息的键。使用let key = Auth.auth().currentUser?.uid代替let key = ref.childByAutoId().key

func profile() {
    guard let key = Auth.auth().currentUser?.uid else { return }
    let email = Auth.auth().currentUser?.email 
    let user = ["id": key,
                "email": email,
                "age": ageTextField.text! as String,
                "gender": genderTextField.text! as String,
                "weight": weightTextField.text! as String,
                "height": heightTextField.text! as String,
                "monthlyGoal": monthlyGoalTextField.text! as String]
    self.ref.child(key).setValue(user)
}

使用currentUser?.uid

从Firebase检索用户详细信息
func getUserDetails() {
    guard let key = Auth.auth().currentUser?.uid else { return }
    self.ref.child(key).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? [String: Any]
        self.emailTextField.text = value?["email"] as? String
        // ...
    }) { (error) in
        print(error.localizedDescription)
    }
}