如何使用coreLocation(iOS/Swift)读取完整地址
代码如下:如何使用coreLocation(iOS/Swift)读取完整地址,ios,swift,xcode,core-location,Ios,Swift,Xcode,Core Location,代码如下: CLGeocoder().reverseGeocodeLocation(myCurrentLoc) { (array, err) in print(err) if err != nil { print(err) return } if let place = array?.first { if let locality = place.loc
CLGeocoder().reverseGeocodeLocation(myCurrentLoc) { (array, err) in
print(err)
if err != nil {
print(err)
return
}
if let place = array?.first {
if let locality = place.locality {
if let country = place.country {
if let addr = place.addressDictionary {
print(addr)
}
let myAddress = "\(locality) \(country)"
self.adress.text = myAddress
self.locMgr.stopUpdatingLocation()
}
}
}
self.locMgr.stopUpdatingLocation()
}
所以我可以读取经度/纬度,我只需要完整的地址。现在我可以打印出“美国纽约”,我发现我需要的所有信息都已准备就绪。但我似乎不能用正常的语法从那本字典里读到任何东西。我该怎么做?我通常会让一个位置管理器助手获取详细信息并使用一个位置标记 您正在谈论的词典带有
placemarks
这是我的模型
class UserLocation: NSObject {
var latitude : String?
var longitude: String?
var timeZone: String?
var city : String?
var state : String?
var country : String?
// you can and more fields of placemark
required init(latitude:String?,longitude:String?,timezone:String?,city:String?,state:String?,country:String?) {
self.latitude = latitude
self.longitude = longitude
self.timeZone = timezone
self.city = city
self.state = state
self.country = country
}
}
然后,在从location Manager获取位置后,我使用下面的代码反转地理编码,并使用placemarks
获取详细信息
//Location Manager delegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.stopUpdatingLocation()
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
if let location = manager.location {
let userLoc = UserLocation(latitude: String(location.coordinate.latitude), longitude: String(location.coordinate.longitude), timezone: NSTimeZone.localTimeZone().name, city: pm.locality!, state: pm.administrativeArea!, country:pm.country!)
//By printing this dictionary you will get the complete address
print(pm.addressDictionary)
print(userLoc.city!)
print(userLoc.state!)
print(userLoc.country!)
print(userLoc.latitude!)
print(userLoc.longitude!)
print(userLoc.timeZone!)
} else {
//Handle error
}
if(!CLGeocoder().geocoding){
CLGeocoder().cancelGeocode()
}
}else{
print("Problem with the data received from geocoder")
}
}
您还可以获取placemark的其他属性,如
我还打印了addressDictionary,您可以在控制台的最后一张图片中看到完整的地址对于美国地址,您可以使用以下地址:
let address = [
place.name,
place.locality,
place.administrativeArea,
place.postalCode,
place.country
]
let formattedAddress = address.flatMap({ $0 }).joined(separator: ", ")
地址
是一组用于组成典型邮政地址的组件。对于某些项目,它可以包含nil
FormattedAddress
删除nils并添加分隔符,我在这里使用了coma。类型为[String]的值在Swift 3中没有“joined”@faterridle的成员。如果您使用较旧的,则有joinWithSeparator