我的布局是这样的
@locationRef
|
@---LtFirstKeyUqABC123
| |--key1:val1
| |--key2:val2
|
@---LtLastKeyrUqXYZ789
| |--key1:val1
| |--key2:val2
|
|---address: "123 Broadway"
|---city: "Bronx"
|---state: "NY"
|---zipcode: "10025"
|---country: "United States"
我只想计算和遍历Firebase
KeyIDs
,而不要遍历其他数据。例如,上面的locationRef
有7个子代,但是在这7个子代中,只有2个是keyIds(LtFirstKeyUqABC123
和LtLastKeyrUqXYZ789
),每个都有自己的2个子代。var startKey: String?
var totalCountOfKeyIds = 0
Database.database().reference().child("locationRef")
.queryOrderedByKey()
.queryLimited(toLast: 10)
.observeSingleEvent(of: .value) { (snapshot) in
if !snapshot.exists() {
self.totalCountOfKeyIds = 0
return
}
for childSnapshot in snapshot.children {
let snap = childSnapshot as! DataSnapshot
// totalCountOfKeyIds = Int(snap.childrenCount) doesn't work
print(Int(snap.childrenCount)) // on every loop this gives me the 2 children under each keyId
if snap.exists() {
// loop through children
guard let children = snap.children.allObjects.first as? DataSnapshot else { return }
for child in snap.children.allObjects as! [DataSnapshot] {
if let dict = child.value as? [String: Any] {
// get dict values
}
}
self.startKey = children.key
}
}
})
完成后,
totalCountOfKeyIds
应该只等于2
,而startKey
应该是LtLastKeyrUqXYZ789
我该怎么做呢?
最佳答案
由于多种原因,在节点下混合不同的实体类型是一个坏主意,其中之一就是您在此处遇到的一个。我建议将您的数据模型重构为具有两个顶级列表,其中名称属性位于其中一个之下,而推送ID位于另一个之下。
也就是说,在您当前的结构上,您可以通过以下方式获得计数:
排除您不想计算的属性。
减去您不想计算的属性数。
其中第一个看起来像这样:
let excludedKeys = ["address", "city", "state", "zipcode", "country"]
Database.database().reference().child("locationRef")
.queryOrderedByKey()
.queryLimited(toLast: 10)
.observeSingleEvent(of: .value) { (snapshot) in
self.totalCountOfKeyIds = 0
for childSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
for child in childSnapshot.children.allObjects as! [DataSnapshot] {
if !excludedKeys.contains(child.key) {
self.totalCountOfKeyIds = self.totalCountOfKeyIds + 1
}
}
}
})
关于ios - Swift -FirebaseDatabase如何计算和迭代仅作为keyIds的子代?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58825207/