Reputation: 2718
Is is possible to query this path in only one go and order the items by locality
value (e.g London), but get only the items which are starting/ending at a certain childByAutoID
?
Reason - when I scroll down in a tableView, I want to get from database more older items ordered by a certain area, e.g London and older than oldestKey
which is the key of the media item.
The first batch of items is downloaded initially using .childAdded
method.
Data:
media
-LgSsaqYzevONPTk2447 // <- childByAutoID
caption: "12"
locality: "City of London"
mediaUID: "-LgSsaqYzevONPTk2447"
-LgSsZnpSNLJwZBNgXGJ
caption: "15"
locality: "New York"
mediaUID: "-LgSsZnpSNLJwZBNgXGJ"
Code
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)
}
})
}
Upvotes: 2
Views: 97
Reputation: 600116
If you know the locality
value of the first item, this is possible with queryStarting(atValue:childKey:)
:
let query = ref.child("media")
.queryOrdered(byChild: "locality")
.queryStarting(atValue: "City of London", childKey: "-LgSsaqYzevONPTk2447")
.queryLimited(toLast: 50)
So the above orders all child nodes by their locality, and then starts returning results at the with with locality
="City of London"
and key -LgSsaqYzevONPTk2447
.
Upvotes: 2