相关疑难解决方法(0)

Swift - 从反向地理编码生成地址格式

我试图使用Swift 3中的CLGeocoder生成格式化的完整地址.我引用了这个SO线程来获取下面给出的代码.

但是,有时应用程序崩溃时会出现"nil"错误:

//Address dictionary
print(placeMark.addressDictionary ?? "")
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 如何连接从GeoCoder检索到的这些值以形成完整地址?(街+城+等)
  2. 当func无法找到地址时,如何处理我得到的nil错误?

完整代码:

func getAddress() -> String {
        var address: String = ""

        let geoCoder = CLGeocoder()
        let location = CLLocation(latitude: selectedLat, longitude: selectedLon)
        //selectedLat and selectedLon are double values set by the app in a previous process

        geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in

            // Place details
            var placeMark: CLPlacemark!
            placeMark = placemarks?[0]

            // Address dictionary
            //print(placeMark.addressDictionary ?? "")

            // Location name
            if let locationName = placeMark.addressDictionary!["Name"] …
Run Code Online (Sandbox Code Playgroud)

xcode google-maps reverse-geocoding ios swift

20
推荐指数
4
解决办法
4万
查看次数

SWIFT - LocationManager循环多次?

我有一个locationManager函数来获取用户当前位置并发布城市和州的名称.我有一个打印声明,所以我可以在我的控制台检查一切是否正常工作......就是这样.但是,它打印城市位置3次.这实际上在我的实际应用程序中引起了一个问题,但这超出了这个问题的范围.

我的功能如下:

var usersLocation: String!

var locationManager: CLLocationManager!

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation: CLLocation = locations[0]


    CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) -> Void in

        if error != nil {

            print(error)

        } else {

            let p = placemarks?.first // ".first" returns the first element in the collection, or nil if its empty
            // this code above will equal the first element in the placemarks array

            let city = p?.locality != nil ? p?.locality : ""
            let state = …
Run Code Online (Sandbox Code Playgroud)

locationmanager ios swift reversegeocodelocation

2
推荐指数
1
解决办法
2121
查看次数