I\'m trying to store coordinates into Firebase Database using GeoFire.
I\'m unsure how to update the new coordinates as they will be changed/updated every second. With
This is my Firebase DB structure for update users location by time and retrive the nearby users to show on map:
db-root
"users" : {
<userUID> : {
"someKey" : "someValue",
...
}
}
"users_location" : {
<userUID> : {
<geofireData> ...
}
}
Vars to use:
let ref = FIRDatabase.database().reference()
let geoFire = GeoFire(firebaseRef: ref.child("users_location"))
To update logged user location:
func updateUserLocation() {
if let myLocation = myLocation {
let userID = FIRAuth.auth()!.currentUser!.uid
geoFire!.setLocation(myLocation, forKey: userID) { (error) in
if (error != nil) {
debugPrint("An error occured: \(error)")
} else {
print("Saved location successfully!")
}
}
}
}
To find nearby user I use the findNearbyUsers
function. It' useful to find the nearby users and save into nearbyUsers
array the UID key of the the users. The observeReady
function is executed after the query completion and uses the UID to retrieve the users details (I use this to show users details on map).
func findNearbyUsers() {
if let myLocation = myLocation {
let theGeoFire = GeoFire(firebaseRef: ref.child("users_location"))
let circleQuery = theGeoFire!.query(at: myLocation, withRadius: radiusInMeters/1000)
_ = circleQuery!.observe(.keyEntered, with: { (key, location) in
if !self.nearbyUsers.contains(key!) && key! != FIRAuth.auth()!.currentUser!.uid {
self.nearbyUsers.append(key!)
}
})
//Execute this code once GeoFire completes the query!
circleQuery?.observeReady({
for user in self.nearbyUsers {
self.ref.child("users/\(user)").observe(.value, with: { snapshot in
let value = snapshot.value as? NSDictionary
print(value)
})
}
})
}
}
Hope it helps