我正在尝试以Swift语言从Firebase数据库(在此示例中为[branch1,branch2])获取分支列表,
当我观察到顶部节点(“分支”)时,它什么也不返回,甚至没有调用第一个打印函数,但是如果观察到像branch1这样的分支之一,它就可以正常工作。
现在如何检索分支列表([branch1,branch2])
let ref = FIRDatabase.database().reference()
ref.child("branches").observe(.value, with: { snapshot in
print("+++++++++++++++++ ")
print("++++++++++++\(snapshot.hasChildren())")
for child in snapshot.children{
let branch = child as! FIRDataSnapshot
let branchName = branch.key as! String
print("\(branchName)")
}
}
enter image description here
{ "Users" : {
"6dICrkbVVJWzVZ00Vq4y9Fm2Qcg2" : {
"branches" : {
"branch1" : true
},
"isAdmin" : true
},
"M0C1XUyboPg5zbgQi24nh3SlJri1" : {
"branches" : {
"branch2" : true
}
} },"branches" : {
"branch1" : {
"address" : "NDG",
"campaigns" : {
"valentine's day" : true
},
"manager" : "y",
"rate" : {
"average" : 0,
"bad" : 0,
"good" : 0
},
"users" : {
"6dICrkbVVJWzVZ00Vq4y9Fm2Qcg2" : true,
"M0C1XUyboPg5zbgQi24nh3SlJri1" : {
"isAdmin" : true
}
}
},
"branch2" : {
"address" : "downtown montreal",
"manager" : "x",
"rate" : {
"average" : 0,
"bad" : 0,
"good" : 0
},
"users" : {
"M0C1XUyboPg5zbgQi24nh3SlJri1" : true,
"Z6b5WalkNWZLMVdwGPHi3vSvSRU2" : {
"isAdmin" : true
}
}
} }, "campaigns" : {
"valentine's day" : {
"branches" : {
"branch1" : true
}
} }}
和获得branch1的工作代码是:
ref.child("branches").child("branch1").observe(.value, with: { snapshot in
let address = snapshot.childSnapshot(forPath: "address").value
print("\(address)")
}
它将打印正确的结果(NDG)
安全规则:
{ "rules": {
"Users":{
"$uid":{
".read":"auth.uid == $uid || root.child('Users').child(auth.uid).child('isAdmin').val()==true",
".write":"auth.uid == $uid || root.child('Users').child(auth.uid).child('isAdmin').val()==true"
}
}, "branches":{
"$branchId":{
".read" : "auth.uid == true || root.child('Users').child(auth.uid).child('isAdmin').val()==true || root.child('branches').child($branchId).child('users').child(auth.uid).exists()",
".write" : "auth.uid == true || root.child('Users').child(auth.uid).child('isAdmin').val()==true || root.child('branches').child($branchId).child('users').child(auth.uid).child('isAdmin').val()==true"
}}}}
最佳答案
感谢@vzsg,我发现问题出在权限和规则上。所以我改变了规则,很容易得到结果
{ "rules": {
"Users":{
"$uid":{
".read":"auth.uid == $uid || root.child('Users').child(auth.uid).child('isAdmin').val()==true",
".write":"auth.uid == $uid || root.child('Users').child(auth.uid).child('isAdmin').val()==true"
}
}, "branches":{
".read": " root.child('Users').child(auth.uid).child('isAdmin').val()==true" ,
".write" : "root.child('Users').child(auth.uid).child('isAdmin').val()==true ",
"$branchId":{
".read": " root.child('branches').child($branchId).child('users').child(auth.uid).exists()",
".write" : "root.child('branches').child($branchId).child('users').child(auth.uid).child('isAdmin').val()==true"
}} }}
关于ios - 通过观察Firebase中的数据库引用无法获取顶级节点的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41708116/