【发布时间】:2019-03-19 10:10:38
【问题描述】:
我正在 swift 4 中编写应用程序。我遇到了关于 reverseGeocoding 的问题。
这是我的代码:
此函数获取当前坐标。
func getCurrentCoordinates(){
var currentLocation: CLLocation!
var locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways){
currentLocation = locManager.location
self.coordGPS = currentLocation
}
}
这个函数转换成地址
func convertLatLongToAddress(latitude:Double,longitude:Double){
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: latitude, longitude: longitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
self.sAddress = ""
/* Location name
if let locationName = placeMark.location {
if(self.bLocalize == true){
print(locationName)
}else{
//self.sAddress = locationName
}
}*/
// Street number
if let number = placeMark.subThoroughfare {
//print(number)
if(self.bLocalize == true){
self.TextFieldStationServiceAdresse.text = placeMark.subThoroughfare! + ", " + self.TextFieldStationServiceAdresse.text!
}else{
self.sAddress = self.sAddress! + ", " + number
}
}
// Street address
if let street = placeMark.thoroughfare {
if(self.bLocalize == true){
print(street)
self.TextFieldStationServiceAdresse.text = street
}else{
self.sAddress = self.sAddress! + ", " + street
}
}
// Zip code
if let zip = placeMark.postalCode {
if(self.bLocalize == true){
print(zip)
self.TextFieldCodePostal.text = zip
}else{
self.sAddress = self.sAddress! + ", " + zip
}
}
// City
if let ville = placeMark.locality {
if(self.bLocalize == true){
self.TextFieldStationServiceCPVille.text = ville
}else{
self.sAddress = self.sAddress! + " " + ville
}
}
// Country
if let country = placeMark.country {
if(self.bLocalize == true){
print(country)
}else{
self.sAddress = self.sAddress! + ", " + country
}
}
})
我的问题是,completionHandler 永远不会被调用。
我导入了 CoreLocation
你能告诉我为什么从不调用 completionHandler 吗?定位服务不适用于此类。
感谢您的帮助。
【问题讨论】:
-
你是从模拟器中选择的位置吗?
-
locManager.location在您的代码中绝对是nil。您必须设置delegate并添加委托方法didUpdateLocations。并且位置管理器将在getCurrentCoordinates结束后被释放,而不保留引用。