我试图用swift获取当前城市名称和国家/地区名称。 这是我的源代码。 //然后在CLLocationManagerDelegate方法中,您可以获取用户的当前位置坐标:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
self.locationManager.stopUpdatingLocation()
getAddressFromGeocodeCoordinate(manager.location!)
}
func getAddressFromGeocodeCoordinate(locationObj: CLLocation) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(locationObj, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// Address dictionary
print(placeMark.addressDictionary)
// City
if let city = placeMark.addressDictionary!["City"] as? NSString {
print("city:",city)
}
// Country
if let country = placeMark.addressDictionary!["Country"] as? NSString {
print("country", country)
}
})
}
但是当我想打印城市时,它返回零。
我也trid placeMark.subAdministrativeArea
但它也返回nil。
我目前位于丹东市。
我的代码打印好国家。比如country China
但是城市。
有谁知道解决方案?
答案 0 :(得分:2)
检查是否有任何错误或获得print(placeMark.addressDictionary)
geocoder.reverseGeocodeLocation(newLocation, completionHandler: {(stuff, error)->Void in
if error {
println("reverse geodcode fail: \(error.localizedDescription)")
return
}
if stuff.count > 0 {
self.placemark = CLPlacemark(placemark: stuff[0] as CLPlacemark)
self.addressLabel.text = String(format:"%@ %@\n%@ %@ %@\n%@",
self.placemark.subThoroughfare ? self.placemark.subThoroughfare : "" ,
self.placemark.thoroughfare ? self.placemark.thoroughfare : "",
self.placemark.locality ? self.placemark.locality : "",
self.placemark.postalCode ? self.placemark.postalCode : "",
self.placemark.administrativeArea ? self.placemark.administrativeArea : "",
self.placemark.country ? self.placemark.country : "")
}
else {
println("No Placemarks!")
return
}
})