Ios 无法获取状态&;swift中带有CLGeoCoder的zipcode?
我无法使用CLGeocoder获取州和邮政编码。我仅获取位置名称、国家和城市。我在印度使用此代码获取位置。我使用以下代码获取此位置Ios 无法获取状态&;swift中带有CLGeoCoder的zipcode?,ios,swift,clgeocoder,Ios,Swift,Clgeocoder,我无法使用CLGeocoder获取州和邮政编码。我仅获取位置名称、国家和城市。我在印度使用此代码获取位置。我使用以下代码获取此位置 func getAddressFromLocation(location: CLLocation) { CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in print(loca
func getAddressFromLocation(location: CLLocation) {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
print(location)
self.activityIndicator.stopAnimating()
if error != nil {
DILog.print(items: "Reverse geocoder failed with error" + (error.debugDescription))
return
}
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
if placeMark == nil {
return
}
// Location name
if let locationName = placeMark.addressDictionary!["Name"] as? String {
self.currentLocation = self.currentLocation + locationName
}
// Street address
if let street = placeMark.addressDictionary!["Thoroughfare"] as? String {
self.currentLocation = self.currentLocation + ", " + street
self.spotLocation.street_address_1 = street
}
// City
if let city = placeMark.addressDictionary!["City"] as? String {
print(city, terminator: "")
self.currentLocation = self.currentLocation + ", " + city
self.spotLocation.city = city
}
// Country
if let country = placeMark.addressDictionary!["Country"] as? String {
print(country, terminator: "")
self.currentLocation = self.currentLocation + ", " + country
self.spotLocation.country = country
}
// Street address
if let street1 = placeMark.addressDictionary!["SubThoroughfare"] as? String {
self.currentLocation = self.currentLocation + ", " + street1
self.spotLocation.street_address_1 = street1
}
// state
if let state = placeMark.addressDictionary!["State"] as? String {
self.currentLocation = self.currentLocation + ", " + state
self.spotLocation.state = state
}
// Zip
if let zip = placeMark.addressDictionary!["Zip"] as? String {
self.currentLocation = self.currentLocation + ", " + zip
self.spotLocation.state = zip
}
self.locationLabel.text? = self.currentLocation
})
}
请告诉我如何获得它的解决方案?您是否打印了
地址字典以查看它包含的内容?为什么将placeMark
声明为隐式展开可选?如果可选(!)数组placemarks
不是nil
,并且它包含一个项,则该项肯定是非可选的。但是,如果数组为空,您的代码将崩溃。我添加了检查placemark是否为零,然后返回placemark
将永远不会为nil
如果placemarks?[0]
成功。但是,如果数组为空,代码将在placemarks?[0]
行崩溃。检查nil
(以及IUO声明)是没有意义的。我将在那里添加检查。感谢您的重要评论。现在您能告诉我我可以再次获取zipcode和state吗:您是否打印地址字典
以查看它包含的内容。它是否包含State
和Zip
键?如果是,值是什么类型的?
let zipCode = placeMark.postalCode ?? "unknown"