I am having a lot of difficulty wrapping my head around completion handlers. And I have no idea how to use this.
Here is the function with the completion handler to obtain geocoordinates based on a string address:
func getLocation(from address: String, completion: @escaping (_ location: CLLocation?)-> Void) {
guard let address = address as? String else { return }
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
guard let placemarks = placemarks,
let location = placemarks.first?.location else {
completion(nil)
return
}
completion(location)
}
}
And I am calling this function like this:
getLocation(from: address) { location in
print("Location is", location.debugDescription)
if case self.currentLocation = location {
self.queryGenerator(searched: self.searchController.isActive, queryString: "")
} else {
self.showAlert(alertTitle: "No businsesses nearby", message: "Try going back and changing the address")
}
}
I keep getting a nil for currentLocation
. If somebody could dumb this down for me, that would be great.
I make a network call after obtaining the location which sends me a custom object that contains the coordinates of the business and a service radius. If the service radius is less than or equal to the distance between the the business coordinates and the currentLocation then I add it to the an array which populates a UITableView. Here is the function where I do the aforementioend calculation:
func applicableRestaurants(allQueriedRestaurants: [Restaurant]) -> [Restaurant] {
var filteredRestaurants = [Restaurant]()
for thisRestaurant in allQueriedRestaurants {
let restaurantCoordinate = CLLocation(latitude: thisRestaurant.geoPoint.latitude, longitude: thisRestaurant.geoPoint.longitude)
if restaurantCoordinate.distance(from: self.currentLocation!) <= thisRestaurant.distance {
filteredRestaurants.append(thisRestaurant)
}
}
return filteredRestaurants
}