我的数据库如下所示
users
|
@--uidABC
|
|---phone:"+13125550690"
|
|---followers
|
|----uid123
| |---timeStamp:111222
|
|----uid456
| |---timeStamp:777999
我使用.observeSingleEvent
检查是否存在uidABC
,如果存在,我想检查该路径下是否存在名为child
的{{1}}。
我可以使用followers
来查看它是否可用以及是否如何遍历下面的所有子对象 snapshot.hasChild("followers")
?
我使用下面的代码,但是它遍历了错误的snapshot.hasChild("...")
。当它应使用snapshot
下的任何DataSnapshot
followers
答案 0 :(得分:0)
使用child
:
// 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
}
}
您可以在此处找到更多信息: Iterate over snapshot children in Firebase
答案 1 :(得分:0)
我从here和这里得到了答案
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
}
}
})