Using GeoFire queries in Swift does not give useful output

此生再无相见时 提交于 2019-12-01 21:55:36

Try writing the locations with GeoFire like this. You don't need to store them under that location key.

let ref = FIRDatabase.database().reference()
let geofireRef = ref.child("users_locations")
let geoFire = GeoFire(firebaseRef: geofireRef)

geoFire?.setLocation(myLocation, forKey: uid!)
Frank van Puffelen

When using Geofire, you have two lists of data:

  1. the list of objects, in your case users
  2. the list of locations for those objects, which is maintained and queries through Geofire

The two lists are indeed meant to be separate. From the Geofire documentation (emphasis mine):

Assume you are building an app to rate bars and you store all information for a bar, e.g. name, business hours and price range, at /bars/<bar-id>. Later, you want to add the possibility for users to search for bars in their vicinity. This is where GeoFire comes in.

You can store the location for each bar using GeoFire, using the bar IDs as GeoFire keys. GeoFire then allows you to easily query which bar IDs (the keys) are nearby. To display any additional information about the bars, you can load the information for each bar returned by the query at /bars/<bar-id>.

I highlighted the two most important bits for your questions:

  1. the items in the list of users and the list of their locations should use the same key (this is what Andrew also pointed out in his answer). By using the same key, you can easily look up the user for a location and vice versa.
  2. you will need to separately load the user for each key within your query.

Andrew shows how to properly write the locations for each user. What is left then is to load the additional information about each user that is in range of the result. You'd do this in he .keyEntered handler:

let usersRef = ref.child("users")

let circleQuery = geoFire?.query(at: center, withRadius: 10)
circleQuery?.observe(.keyEntered, with: { (key: String?, location: CLLocation?) in

     print("Key '\(key!)' entered the search are and is at location '\(location!)'")
     // Load the user for the key
     let userRef = usersRef.child(key)
     userRef.observeSingleEvent(FIRDataEventType.value, with: { (snapshot) in
         let userDict = snapshot.value as? [String : AnyObject] ?? [:]
         // ...
     })
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!