如何使用 Swift 在 Firebase 中查询最近的用户?

How to query nearest users in Firebase with Swift?

我想找到离我最近的用户。 (例如最多 5 公里)我在 firebase 数据库中的节点如下结构,

+ users
  + user_id0
    - latitude: _
    - longitude: _

有没有什么方法可以在该半径内获得准确的用户。否则我应该使用 CLLocation distance 方法检查每个用户离我最近的位置。

我强烈建议使用 Geofire 来做这样的事情。

要设置它,您的数据结构会略有变化。您仍然可以将 lat/lng 存储在您的用户身上,但您还将创建一个新的 Firebase table,名称类似于 users_locations

您的 users_locations table 将通过 Geofire 填充,看起来像这样

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

通常,这就是您在 Geofire 中存储位置的方式,但您可以将其设置为在创建/更新用户对象时保存位置。

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

当您在 users_locations 中保存您的位置后,您可以使用 GFQuery 查询特定范围内的所有用户。

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)'")
})