Reputation: 75
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 the childByAutoId
, it is generating a new unique ID for each Bike.
How do I reference this unique Bike ID? For instance, the user would be called by FIRAuth.auth()?.currentUser?.uid
. Is this possible?
let geofireRef = FIRDatabase.database().reference().child("Bike").childByAutoId()
let geoFire = GeoFire(firebaseRef: geofireRef)
var data = geoFire?.setLocation(CLLocation(latitude: userIncrementLat, longitude: userIncrementLong), forKey: "BikeId")
My Firebase Database Structure will look like...
Root
1. Bike
2. UniqueUID Number (Firebase)
3. BikeId
4. g
l
5. 0:
1:
Upvotes: 3
Views: 4286
Reputation: 697
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
Upvotes: 6