这是我的Firebase树的快速输出,id类似于访问people_on_this_planit / userID节点。我唯一的问题是节点在自动ID内;请任何帮助将不胜感激。感谢
planits
-LEmgxuG_13KNA5inRaB
Planit Title: "Some title"
people_on_planit
-LEmh6IxqguVBJEwghZv (auto ID)
userID: "kkdiEW0D9"
senderId: "39FdLfdIO8832"
现在我正在使用的代码如下,但是当我打印peopleonplanit时我得到的是nil。
ref = Database.database().reference()
let userID = Auth.auth().currentUser?.uid
let planitsRef = ref.child("planits")
for child in snapshot.children {
let childSnap = child as! DataSnapshot
let dict = childSnap.value as! NSDictionary
let planKey = childSnap.key
//print(planKey)
print(dict)
let title = dict["Planit Title"] as! String
let senderID = dict["senderId"] as! String
let peopleOnPlanit = dict["people_on_planit"] as? String
print(peopleOnPlanit)
}
答案 0 :(得分:1)
以下是阅读问题中提出的Firebase结构的代码
let planitsRef = self.ref.child("planits")
planitsRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let planSnap = child as! DataSnapshot
let planDict = planSnap.value as! [String: Any]
let title = planDict["plan_title"] as! String
let senderId = planDict["sender_id"] as! String
print("plan title: \(title) senderId: \(senderId)")
let peopleOnPlanitSnap = planSnap.childSnapshot(forPath: "people_on_planit")
for peopleChild in peopleOnPlanitSnap.children {
let peopleChildSnap = peopleChild as! DataSnapshot
let userSnapDict = peopleChildSnap.value as! [String: Any]
let userId = userSnapDict["user_id"] as! String
print(" userId: \(userId)")
}
}
})
和输出
plan title: Some title senderId: 39FdLfdIO8832
userId: uid_0
userId: uid_1
- 几个笔记 -
由于关联用户似乎是由他们的用户ID存储的,并且这是该节点中存储的唯一数据,因此您可能想要更改此节点
people_on_planit
-LEmh6IxqguVBJEwghZv (auto ID)
userID: "kkdiEW0D9"
看起来像这样
people_on_planit
uid_x: true //uid_x would be kkdiEW0D9 etc
uid_y: true
它更浅,更清洁,需要更少的代码来读取它。此外,如果出现这种情况,您可以更轻松地查询它。
还要注意我稍微更改了命名约定;欢迎您按照自己的意愿格式化键,但我使用了 plan_title 等键,而不是 PlanIt Title 和 sender_id 和 user_id 而不是senderId和userId。我的实践是实际的firebase键我使用全部小写,下划线而不是空格,在代码中,我使用低/大写没有空格。因此,如果您复制粘贴我的代码,则需要更改这些代码。