Database layout is
root
posts
-postId_1
-userId
-other data
-postId_2
-userId
-other data
When a user wants to scroll through all posts (location irrelevant) I paginate based on postId using:
let postsRef = Database.database().reference().child("posts")
if startKey == nil {
postsRef.queryOrderedByKey().queryLimited(toLast: 20).observeSingleEvent(of: .value) { [weak self](snapshot) in
guard let firstChild = snapshot.children.allObjects.first as? DataSnapshot else { return }
let arr = snapshot.children.allObjects as! [DataSnapshot]
for child in arr.reversed() {
let postId = child.key
guard let dict = child.value as? [String:Any] else { return }
// create a post, append to datasource ...
}
self?.startKey = firstChild.key
}
else {
postsRef.queryOrderedByKey().queryEnding(atValue: startKey!).queryLimited(toLast: 21).observeSingleEvent(of: .value) { (snapshot) in
// same as above ...
}
}
When I want to query other users based on their location in proximity to the current user I use:
let radius = (10 * 2) * 1609.344 // this is 10 miles
guard let currentLocation = locationManager.location else { return }
let lat = currentLocation.coordinate.latitude
let lon = currentLocation.coordinate.longitude
let location = CLLocation(latitude: lat, longitude: lon)
let region = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: radius, longitudinalMeters: radius)
let geofireRef = Database.database().reference().child("geo")
let geoFire = GeoFire(firebaseRef: geofireRef)
regionQuery = geoFire.query(with: region)
queryHandle = regionQuery?.observe(.keyEntered, with: { [weak self](key: String!, location: CLLocation!) in
let userId = key
let userLocation = location
self?.arrOfUserIds.append(userId)
}
regionQuery?.observeReady({ [weak self] in
self?.paginateBasedOnUserIdReturnedFromRegionQuery()
}
Everything above works fine. The problem is when the regionQuery?.observeReady
is called, I have an array of all the userIds in the surrounding 10 mile radius. That can be 1 user or 1000 users and each user can have 1 post or 100+ posts. I can't figure out how to paginate the posts ref based on userId.
Each post has a userId but in the first example above I'm paginating based on postId
. I want to paginate the posts ref based on the userIds returned from the regionQuery like
func paginateBasedOnUserIdReturnedFromRegionQuery() {
for userId in arrOfUserIds {
// how to paginate the posts ref using the userId ???
}
}