I\'m pretty desperate right now because I\'m trying to use GeoFire on my Firebase Database to find nearby users. I\'m pretty much stuck for two days now. I searched Google a
When using Geofire, you have two lists of data:
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:
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] ?? [:]
// ...
})
})
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!)