Swift中的反向地理编码位置[关闭]

问题描述 投票:24回答:1

我的输入是纬度和经度。我需要使用swift的reverseGeocodeLocation函数,以提供局部性的输出。我尝试使用的代码是

            println(geopoint.longitude) 
            println(geopoint.latitude)
            var manager : CLLocationManager!
            var longitude :CLLocationDegrees = geopoint.longitude
            var latitude :CLLocationDegrees = geopoint.latitude

            var location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
            println(location)

            CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error) -> Void in
                println(manager.location)

                if error != nil {
                    println("Reverse geocoder failed with error" + error.localizedDescription)
                    return
                }
                if placemarks.count > 0 {
                    let pm = placemarks[0] as CLPlacemark


                    println(pm.locality)
                }


                else {
                    println("Problem with the data received from geocoder")
                }

在我得到的日志中

//-122.0312186
//37.33233141
//C.CLLocationCoordinate2D
//fatal error: unexpectedly found nil while unwrapping an Optional value

CLLocationCoordinate2DMake函数似乎失败,然后在reverseGeocodeLocation函数中导致致命错误。我是否在某处修改了格式?

ios swift cllocationmanager reverse-geocoding
1个回答
67
投票

您从不对地理位置进行地理编码,但您传入manager.location。

请参阅:CLGeocoder().reverseGeocodeLocation(manager.location, ...

我认为这是一个复制粘贴错误,这是问题所在-代码本身看起来不错-几乎;)

工作代码

    var longitude :CLLocationDegrees = -122.0312186
    var latitude :CLLocationDegrees = 37.33233141

    var location = CLLocation(latitude: latitude, longitude: longitude) //changed!!!
    println(location)

    CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
        println(location)
        guard error == nil else {
            println("Reverse geocoder failed with error" + error.localizedDescription)
            return
        }
        guard placemarks.count > 0 else {
            println("Problem with the data received from geocoder")
            return
        }
        let pm = placemarks[0] as! CLPlacemark
        println(pm.locality)
    })
© www.soinside.com 2019 - 2024. All rights reserved.