我试图用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)")
}
}
{ "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"
}}}}
答案 0 :(得分:0)
感谢@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"
}} }}