检索用户根集合引用同级集合的 Firebase 数据



使用此路径在Firebase中访问所有地图可以完美运行,但是它会抓取"地图"根集合中的所有可用地图。

let yourMapRef = Database.database().reference().child("Maps")

我尝试仅访问用户所属的地图。因此,我尝试遵循堆栈问题和火力基础教程,但我无法掌握如何做到这一点。

例如,我希望亚当只抓住他的审核地图

let yourMapRef = Database.database().reference().child("users/(userProfile.uid)/Maps")

我应该如何思考这个问题,如何解决这个问题?

用户(根集合结构(

{
"4g99cMTM4begwooORsO4EKNV456" : {
"username" : "Adam",
"Maps" : {
"-LpYo_pQ8zIOGHHlNU1Q" : true
}
},
"6g55cHXH4begwooHQvO4EKNV3xm1" : {
"username" : "Ellen",
"Maps" : {
"-LpY4XEER-b21hwMi9sp" : true
}
}
}

映射(根集合结构(

{
"-LpY4XEER-b21hwMi9sp" : {
"mapmoderators" : {
"6g55cHXH4begwooHQvO4EKNV3xm1" : true
},
"mapphotoURL" : "https://firebasestorage.googleapis.com/v0/b/...",
"mapusername" : "Hello World"
},
"-LpYo_pQ8zIOGHHlNU1Q" : {
"mapmoderators" : {
"4g99cMTM4begwooORsO4EKNV456" : true
},
"mapphotoURL" : "https://firebasestorage.googleapis.com/v0/...",
"mapusername" : "Dream"
}
}

因此,您要做的是首先获取用户,然后将其用于地图集合,以检查他们是否审核地图:

func getUsers() {
let userRef = Database.database().reference().child("users").child(currentUserID)
userRef.observeSingleEvent(of: .value, with: { (snapshot) in
let root = snapshot.value as? Dictionary
if let mapsByUser = root["Maps"] as? [String: Bool] {
for (documentId, status) in mapsByUser {
if status {
// Document is true, check for the maps
self.getMaps(key: documentId, owner: currentUserID)
}
}
}
}) { (error) in
print(error.localizedDescription)
}
}
// Check for maps
func getMaps(key:String, owner:String) {
let userRef = Database.database().reference().child("maps").child(key)
userRef.observeSingleEvent(of: .value, with: { (snapshot) in
let user = snapshot.value as? Dictionary
if let mapsByUser = user["mapmoderators"] as? [String: Bool] {
for (userId, status) in mapsByUser {
if userId == owner && status == true {
print("Owner (owner) manages this (user)")
}
}
}
}) { (error) in
print(error.localizedDescription)
}
}

在 viewDidLoad 上调用getUsers()来测试这一点。

最新更新