如何使用Swift查询Firebase中最近的用户? [英] How to query nearest users in Firebase with Swift?

查看:150
本文介绍了如何使用Swift查询Firebase中最近的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to find nearest users to my location. (For example up to 5km) My nodes in firebase database like below structure,

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

有没有办法获得确切的用户在那个半径里。否则我应该使用 CLLocation distance 方法检查每个用户最近的位置。

Is there any way getting exact users in that radius. Otherwise I should check each user of them nearest position or not to me using CLLocation distance method.

推荐答案

我强烈建议您使用 Geofire

要进行设置,您的数据结构会略有变化。你仍然可以在你的用户上存储lat / lng,但你也会创建一个新的Firebase表,其名称类似于 users_locations

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

你的 users_locations 表将通过Geofire填充,看起来像这样

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

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

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

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

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

这篇关于如何使用Swift查询Firebase中最近的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆