Ios Firebase-如何循环使用snapshot.hasChild(“…”)
我的数据库如下所示Ios Firebase-如何循环使用snapshot.hasChild(“…”),ios,swift,loops,firebase-realtime-database,Ios,Swift,Loops,Firebase Realtime Database,我的数据库如下所示 users | @--uidABC | |---phone:"+13125550690" | |---followers | |----uid123 | |---timeStamp:111222 | |----uid456 |
users
|
@--uidABC
|
|---phone:"+13125550690"
|
|---followers
|
|----uid123
| |---timeStamp:111222
|
|----uid456
| |---timeStamp:777999
我使用.observeSingleEvent
检查uidABC
是否存在,如果存在,我想检查该路径下是否有名为追随者的子项
我可以使用snapshot.hasChild(“followers”)
查看它是否可用,以及它是否如何循环遍历snapshot.hasChild(“…”)下的所有子项
我使用下面的代码,但它在错误的快照中循环。当它应该使用DataSnapshot
下的followers
let ref = Database...child("users").child(uidABC)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists() {
// this user doesn't exist
return
}
if !snapshot.hasChild("followers") {
// this user exists but has no followers
return
}
// this user exists and has followers now loop through them
for uid in snapshot.children {
let snapshot = uid as! DataSnapshot
if let dict = snapshot.value as? [String:Any] {
let timeStamp = dict["timeStamp"] as? Double
// eg. check for a specific timeStamp
}
}
})
使用子项
:
// this user exists and has followers now loop through them
for uid in snapshot.childSnapshot("followers") {
guard let snapshot = uid as! DataSnapshot else {
// Followers error
}
if let dict = snapshot.value as? [String:Any] {
let timeStamp = dict["timeStamp"] as? Double
// eg. check for a specific timeStamp
}
}
您可以在此处找到更多信息:
我从这里得到了答案
谢谢,我试过了,但是得到了一个错误-类型为'DataSnapshot'的值没有成员'child';你是说“孩子”吗?child
被重命名为childSnapshot(forPath:)
谢谢你纠正我:)@LanceSamariaI我都不知道我在纠正你。我以为你正在关闭一个完全不同的快照子属性。谢谢你的帮助
let ref = Database...child("users").child(uidABC)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if !snapshot.exists() {
// this user doesn't exist
return
}
if !snapshot.hasChild("followers") {
// this user exists but has no followers
return
}
// this user exists and has followers now loop through them
let childSnapshot = snapshot.childSnapshot(forPath: "followers") {
for child in childSnapshot.children {
let snap = child as! DataSnapshot
let uid = snap.key
if let dict = snap.value as? [String: Any] {
let timeStamp = dict["timeStamp"] as? Double ?? 0
// eg. check for a specific timeStamp
}
}
})