Swift中的反向地理编码位置

时间:2014-12-15 23:55:40

标签: ios swift cllocationmanager reverse-geocoding

我的输入是纬度和经度。我需要使用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函数中的致命错误。我在某个地方搞砸了格式吗?

1 个答案:

答案 0 :(得分:66)

你永远不会反转地理编码的位置,但是你传递了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)

        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")
        }
    })