swift - 从地址获取坐标的完成处理程序
问题描述
我在完成处理程序周围有很多困难。而且我不知道如何使用它。
这是带有完成处理程序的函数,用于根据字符串地址获取地理坐标:
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
}
解决方案
我的猜测(这只是一个猜测)是你在不理解它的含义的情况下使用了这个表达式:
if case self.currentLocation = location {
self.queryGenerator...
我想你的意思可能是:
if let location = location {
self.currentLocation = location
self.queryGenerator...
我想你可能认为这些是等价的,但事实并非如此。
推荐阅读
- avaloniaui - Avalonia UI,通过绘制事物创建自定义控件
- java - OneToMany 双向关系不在子实体中插入外键
- python - 有没有办法获得 tkinter 正方形的颜色?
- gradle - 从脚本返回的 Gradle 导出环境
- python - 为什么 jQuery 支持的注册按钮没有响应?
- android-constraintlayout - android constraintlayout,椭圆不能按预期工作
- r - read.csv 在 R 中将列名向右移动
- javascript - ReactJS动态更改背景图像不起作用
- c++ - 为什么模板类的内联静态变量未初始化?
- recursion - P5js 显示递归发生