【问题标题】:how can i get user postalcode我怎样才能得到用户的邮政编码
【发布时间】:2017-03-15 13:43:26
【问题描述】:

我正在使用 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)
}    

代码中没有错误,但如果我刚刚删除“getlocation = placemarks.postalCode!”,应用程序会崩溃该应用程序不会崩溃,但我无法获取邮政编码。它正在 swift 2 上运行。有什么帮助可以解决这个问题吗?

【问题讨论】:

    标签: swift swift3 cllocationmanager


    【解决方案1】:

    正如@ashley-mills 指出的那样,它们是两种不同类型的信息。当您期望可能出现零时,或者即使您不期望它,最好的解决方案是通过以下方式保护您自己免受现金伤害。

    guard let getlocation = placemarks.postalCode else { print("Returned Nil"); return }
    print(getlocation) // notice no unwrap need
    

    【讨论】:

      【解决方案2】:

      问题通过改变解决:

      getlocation = placemarks.postalCode!
      

      到:

      getlocation = placemarks.isoCountryCode!
      

      我不知道有什么区别,也许邮政编码在 swift 3 中不起作用?

      【讨论】:

      • postalCodeisoCountryCode 是完全不同的东西。一个类似于邮政编码或英国邮政编码,另一个是国家/地区代码。可能您所在的区域没有postalCode - 但这里真正的问题是您强制解包变量。 不要!
      • 哦,谢谢你的解释!我认为“isoCountryCode”这就是我一直在寻找的我只想获取国家代码来设置用户所在的标志。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多