This question already has answers here:
Code only retrieving one value from data in Firebase
(2个答案)
去年关门了。
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!)
    { (user, error) in

        if error != nil {
            print(error!)
            self.warningLabel.isHidden = false;
            self.passwordTextField.text = "";
        } else {
            guard let uid = Auth.auth().currentUser?.uid else {
                print("no uid");
                return
            }

            //PROBLEM AREA
            let databaseRef = Database.database().reference().child("users/\(uid)/profile")

            databaseRef.observe(.value, with: { (snapshot) in
                print("profile: \(snapshot)")

                if(snapshot.exists()) {
                    let array:NSArray = snapshot.children.allObjects as NSArray

                    for obj in array {
                        let snapshot:DataSnapshot = obj as! DataSnapshot
                        if let childSnapshot = snapshot.value as? [String : AnyObject]
                        {
                            if let name = childSnapshot["name"] as? String {
                                print(name)
                            } else {
                                print("no name retrieved");
                            }
                            if let profileImageURL = childSnapshot["profileImageURL"] as? String {
                                print(profileImageURL)
                            } else {
                                print("no profile image retrieved");
                            }
                        }
                    }

                }
            }


            print("Log in succesful")
            self.performSegue(withIdentifier: "welcomeSeg", sender: self)
        }
    }

}

我发现文档(或者我的搜索技能)有点缺乏。我的配置文件快照只是显示为空,虽然我确定那里有数据。
我的数据库布局如下:
swift - 无法访问实时数据库中存储的对象-LMLPHP

最佳答案

你在观察一个用户的个人资料。这意味着您的快照包含该单个用户的属性,您不需要像现在这样循环其子级。
所以像这样:

let databaseRef = Database.database().reference().child("users/\(uid)/profile")

databaseRef.observe(.value, with: { (snapshot) in
    if(snapshot.exists()) {
        if let childSnapshot = snapshot.value as? [String : AnyObject] {
          if let name = snapshot["name"] as? String {
            print(name)
          } else {
            print("no name retrieved");
          }
          if let profileImageURL = snapshot["profileImageURL"] as? String {
            print(profileImageURL)
          } else {
            print("no profile image retrieved");
          }
        }
    }
}

关于swift - 无法访问实时数据库中存储的对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50779827/

10-15 19:09
查看更多