无法访问存储在实时数据库中的对象

时间:2018-06-10 01:18:12

标签: swift firebase firebase-realtime-database

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)
        }
    }

}

我发现文档(或者我的搜索技巧)有点缺乏。我的个人资料快照只显示为空,但我确定那里有数据。

我的数据库布局如下:

database layout

1 个答案:

答案 0 :(得分:2)

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

这样的事情:

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");
          }
        }
    }
}