【发布时间】:2020-04-16 16:29:02
【问题描述】:
我很难理解完成处理程序。而且我不知道如何使用它。
这里是带有完成处理程序的函数,用于根据字符串地址获取地理坐标:
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)
}
}
我这样调用这个函数:
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")
}
}
currentLocation 一直是零。如果有人能帮我把这件事简化一下,那就太好了。
我在获取位置后进行网络调用,该位置向我发送了一个包含业务坐标和服务半径的自定义对象。如果服务半径小于或等于业务坐标和 currentLocation 之间的距离,那么我将其添加到填充 UITableView 的数组中。这是我进行前面计算的函数:
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
}
【问题讨论】:
-
guard let address = address as? String else { return }你可能想做completion(nil)以防地址不好,但这很奇怪,因为address不应该是可选的。placemarks是零吗?geocodeAddressString()中触发了哪种情况? -
对不起,我不太明白。如果位置无法解析,我确实有完成(无)。
-
知道了。我在上面的问题中添加了功能和解释。