我怎样才能得到用户邮政编码
how can i get user postalcode
我正在使用 swift 3. 我在使用此代码获取这样的邮政编码时遇到问题 "US" 并将其保存到 var.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
if error != nil {
print("Location Error!")
return
}
if let pm = placemarks?.first {
self.showlocation(pm)
} else {
print("error with data")
}
})
}
func showlocation(_ placemarks: CLPlacemark) {
self.locationm.stopUpdatingLocation()
print("Location done")
// getlocation = placemarks.postalCode! "this string var is nil"
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location Error: " + error.localizedDescription)
}
代码中没有错误,但应用程序崩溃创建 nil,如果我刚刚删除 "getlocation = placemarks.postalCode!" 应用程序不会崩溃,但我无法获取邮政编码。它正在 swift 2 上工作。是否可以帮助解决此问题?
通过更改解决了问题:
getlocation = placemarks.postalCode!
至:
getlocation = placemarks.isoCountryCode!
我不知道有什么区别,也许邮政编码在 swift 3 中不起作用?
正如@ashley-mills 所指出的,它们是两种不同类型的信息。当您期望 nil 是可能的,或者即使您不期望它时,最好的解决方案是使用以下类似的方法保护您自己免受现金侵害。
guard let getlocation = placemarks.postalCode else { print("Returned Nil"); return }
print(getlocation) // notice no unwrap need
我正在使用 swift 3. 我在使用此代码获取这样的邮政编码时遇到问题 "US" 并将其保存到 var.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
if error != nil {
print("Location Error!")
return
}
if let pm = placemarks?.first {
self.showlocation(pm)
} else {
print("error with data")
}
})
}
func showlocation(_ placemarks: CLPlacemark) {
self.locationm.stopUpdatingLocation()
print("Location done")
// getlocation = placemarks.postalCode! "this string var is nil"
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location Error: " + error.localizedDescription)
}
代码中没有错误,但应用程序崩溃创建 nil,如果我刚刚删除 "getlocation = placemarks.postalCode!" 应用程序不会崩溃,但我无法获取邮政编码。它正在 swift 2 上工作。是否可以帮助解决此问题?
通过更改解决了问题:
getlocation = placemarks.postalCode!
至:
getlocation = placemarks.isoCountryCode!
我不知道有什么区别,也许邮政编码在 swift 3 中不起作用?
正如@ashley-mills 所指出的,它们是两种不同类型的信息。当您期望 nil 是可能的,或者即使您不期望它时,最好的解决方案是使用以下类似的方法保护您自己免受现金侵害。
guard let getlocation = placemarks.postalCode else { print("Returned Nil"); return }
print(getlocation) // notice no unwrap need