How to query nearest users in Firebase with Swift?

眉间皱痕 提交于 2019-11-27 09:10:50

I'd highly recommend using Geofire for something like this.

To set it up, your data structure will slightly change. You can still store lat/lng on your users, but you will also create a new Firebase table called something like users_locations

Your users_locations table will be populated through Geofire, and will look something like this

users_locations
  user_id0:
    g: 5pf666y
    l:
      0: 40.00000
      1: -74.00000

In general, this is how you would store a location in Geofire, but you can set it up to save whenever your user object is created / updates location.

let geofireRef = FIRDatabase.database().reference().child("users_locations")
let geoFire = GeoFire(firebaseRef: geofireRef)
geoFire.setLocation(CLLocation(latitude: lat, longitude: lng), forKey: "user_id0")

When you've saved your locations in users_locations, you can then use a GFQuery to query for all the users in a certain range.

let center = CLLocation(latitude: yourLat, longitude: yourLong)
var circleQuery = geoFire.queryAtLocation(center, withRadius: 5)

var queryHandle = circleQuery.observeEventType(.KeyEntered, withBlock: { (key: String!, location: CLLocation!) in
   println("Key '\(key)' entered the search area and is at location '\(location)'")
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!