可以只查询一次该路径,并按locality
值对商品进行排序(例如伦敦),但仅获取在某处开始/结束的商品childByAutoID
?
原因-当我在tableView中向下滚动时,我想从数据库中获取按某个区域排序的更多旧商品,例如伦敦,并且旧于oldestKey
,这是媒体项目。
最初使用.childAdded
方法下载第一批项目。
数据:
media
-LgSsaqYzevONPTk2447 // <- childByAutoID
caption: "12"
locality: "City of London"
mediaUID: "-LgSsaqYzevONPTk2447"
-LgSsZnpSNLJwZBNgXGJ
caption: "15"
locality: "New York"
mediaUID: "-LgSsZnpSNLJwZBNgXGJ"
代码
class func observeNewMediaSingleTime(_ oldestKey: String,_
userLocality: String, _ completion: @escaping ([Media], String?) -> Void) {
let ref = Database.database().reference()
let query = ref.child("media").queryOrdered(byChild: userLocality).queryStarting(atValue: oldestKey).queryLimited(toLast: 50)
ref.observeSingleEvent(of: .value, with: { snapshot in
guard snapshot.exists() else {
completion([],nil)
return}
let firstItem = snapshot.children.allObjects.first as! DataSnapshot
var arrayOfMedia = [Media]()
var count = 0
let enumerator = snapshot.children
while let mediaItem = enumerator.nextObject() as? DataSnapshot {
let media = Media(dictionary: mediaItem.value as! [String:Any])
print("media.locality is \(media.locality)")
//check if new media has same key as oldest post downloaded in previously
if media.mediaUID != oldestKey{
count += 1
arrayOfMedia.append(media)
}
}//end of while
arrayOfMedia.reverse()
if count == arrayOfMedia.count {
let updatedOldestKey = firstItem.key
completion(arrayOfMedia, updatedOldestKey)
}
})
}
答案 0 :(得分:2)
如果您知道第一项的locality
值,则可以使用queryStarting(atValue:childKey:)
:
let query = ref.child("media")
.queryOrdered(byChild: "locality")
.queryStarting(atValue: "City of London", childKey: "-LgSsaqYzevONPTk2447")
.queryLimited(toLast: 50)
因此,以上方法按其位置对所有子节点进行排序,然后开始使用locality
= "City of London"
和键-LgSsaqYzevONPTk2447
从处返回结果。