我正在尝试从当前登录的用户中检索特定数据。我的数据库中的数据如下所示:
例如,我想抓取full_name并将其保存在变量userName中。以下是我用来获取数据的内容
ref.queryOrderedByChild("full_name").queryEqualToValue("userIdentifier").observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
print(snapshot.value)
// let userName = snapshot.value["full_name"] as! String
})
不幸的是,这就是我的控制台打印的内容。
我将不胜感激任何帮助:)谢谢!
答案 0 :(得分:12)
它会向您发出警告消息indexOn
,因为您正在进行查询。
您应该通过.indexOn定义要编入索引的键 您的安全和Firebase规则中的规则。虽然你被允许 在客户端上临时创建这些查询,你会看到很多 使用.indexOn时提高了性能
如您所知,您可以直接转到该节点,无需查询。
let ref:FIRDatabaseReference! // your ref ie. root.child("users").child("stephenwarren001@yahoo.com")
// only need to fetch once so use single event
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
if !snapshot.exists() { return }
//print(snapshot)
if let userName = snapshot.value["full_name"] as? String {
print(userName)
}
if let email = snapshot.value["email"] as? String {
print(email)
}
// can also use
// snapshot.childSnapshotForPath("full_name").value as! String
})
答案 1 :(得分:3)
Swift 4
let ref = Database.database().reference(withPath: "user")
ref.observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() { return }
print(snapshot) // Its print all values including Snap (User)
print(snapshot.value!)
let username = snapshot.childSnapshot(forPath: "full_name").value
print(username!)
})
答案 2 :(得分:2)
{
"rules": {
"tbl_name": {
".indexOn": ["field_name1", "field_name2"]
},
".read": true,
".write": true
}
}
您可以在任何字段上应用indexOn。在规则安全性和规则选项卡中添加此json。 希望这对你有用。 :)
答案 3 :(得分:2)
它检索登录的用户数据:
let ref = FIRDatabase.database().reference(fromURL: "DATABASE_URl")
let userID = FIRAuth.auth()?.currentUser?.uid
let usersRef = ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
答案 4 :(得分:2)
let ref = Database.database().reference().child("users/stephenwarren001@yahoo.com")
ref.observeSingleEvent(of: .value, with: { (snap : DataSnapshot) in
print("\(String(describing: snap.value))")
}) { (err: Error) in
print("\(err.localizedDescription)")
}
答案 5 :(得分:0)
var refDatabase = DatabaseReference()
refDatabase = Database.database().reference().child("users");
let refUserIdChild = refDatabase.child("stephenwarren001@yahoo.com")
refUserIdChild.observeSingleEvent(of: .value, with: { snapshot in
if !snapshot.exists() { return }
print(snapshot) // Its print all values including Snap (User)
print(snapshot.value!)
if let tempDic : Dictionary = snapshot.value as? Dictionary<String,Any>
{
if let userName = tempDic["full_name"] as? String {
self.tfName.text = userName
}
if let email = tempDic["email"] as? String {
self.tfEmail.text = email
}
}
})