I'm trying to retrieve all available drivers from my Firebase Database, then maybe put them in an array, So I can Calculate which driver is closer to a user. Or is there a better way of doing it than Array
Here is my Code Below for Retrieving the drivers, Its working and Below is the image for my database table
ref.child("drivers").queryOrdered(byChild: "status").queryEqual(toValue: "available").observe(.childAdded) { (snapshot) in
print(snapshot.value!)
}
Here is a Code that would sort out the closest driver to a user but I need to sort out drivers into an array first
var closestLocation: CLLocation?
var smallestDistance: CLLocationDistance?
for location in locations {
let distance = currentLocation.distanceFromLocation(location)
if smallestDistance == nil || distance < smallestDistance {
closestLocation = location
smallestDistance = distance
}
}
print("smallestDistance = \(smallestDistance)")
To populate an array from Firebase, we need to take each driver node, obtain the child nodes we are interested in, group them up and add them to an array.
To do that we are going to take the presented Snapshot, map it to a Dictionary and then read the child nodes by their keys. Then leverage a Structure to hold the distance and drivers name in an array.
Keep in mind that using .childAdded will iterate over all of the existing nodes once, and then call the code in the closure any time a new child is added - you may want to consider reading the node once with .value and iterate over the nodes in that snapshot instead (i.e. .observeSingleEvent(of: .value))
Here's some very verbose code to read your drivers node and add them, and their distance from our current location into an array.
Please be aware that Firebase is asynchronous so processing the array distances should be done within the closure and any code following this code will run before this code completes.
struct DriverAndDistance {
var driver = ""
var distance = 0.0
}
var driverArray = [DriverAndDistance]()
func readDriversAndAddObserver() {
let driversRef = self.ref.child("drivers")
driversRef.observe(.childAdded, with: { snapshot in
if snapshot.exists() == false { return }
let dict = snapshot.value as! [String: Any]
let firstName = dict["Firstname"] as! String
let long = dict["long"] as! Double
let lat = dict["lat"] as! Double
let distanceFromHere = self.getDistance(long, lat)
let dd = DriverAndDistance(driver: firstName, distance: distanceFromHere)
self.driverArray.append(dd)
//do calculations here and present data to user
})
}