gpt4 book ai didi

iOS Swift 坐标函数返回 nil

转载 作者:搜寻专家 更新时间:2023-11-01 06:23:54 24 4
gpt4 key购买 nike

我正在研究将城市(字符串)转换为坐标的函数。但是,当我调用该函数时,结果是“(0.0, 0.0)”。应该是经纬度。

请帮帮我。谢谢!

这是函数

func getCoordinates(huidigeLocatie: String) -> (lat: CLLocationDegrees, long: CLLocationDegrees) {

var lat:CLLocationDegrees
var long:CLLocationDegrees

var geocoderHuidigeLocatie = CLGeocoder()

geocoderHuidigeLocatie.geocodeAddressString(huidigeLocatie, completionHandler:
{(placemarks: [AnyObject]!, error: NSError!) in

if error != nil {

println("Geocode failed with error: \(error.localizedDescription)")

} else if placemarks.count > 0 {

let placemark = placemarks[0] as CLPlacemark
let location = placemark.location

var lat = location.coordinate.latitude
var long = location.coordinate.longitude

}
})

return (lat: CLLocationDegrees(), long: CLLocationDegrees())
}

最佳答案

这里有两个问题:

  1. 您想返回实际的 latlong 变量,而不是 CLLocationDegrees()

  2. 一个更微妙的问题是您正在调用一个异步返回其结果的函数,因此您无法立即返回值。相反,您可以使用自己的 completionHandler 模式。

例如:

func getCoordinates(huidigeLocatie: String, completionHandler: (lat: CLLocationDegrees!, long: CLLocationDegrees!, error: NSError?) -> ()) -> Void {

var lat:CLLocationDegrees
var long:CLLocationDegrees

var geocoderHuidigeLocatie = CLGeocoder()

geocoderHuidigeLocatie.geocodeAddressString(huidigeLocatie) { (placemarks: [AnyObject]!, error: NSError!) in

if error != nil {

println("Geocode failed with error: \(error.localizedDescription)")

completionHandler(lat: nil, long: nil, error: error)

} else if placemarks.count > 0 {

let placemark = placemarks[0] as CLPlacemark
let location = placemark.location

let lat = location.coordinate.latitude
let long = location.coordinate.longitude

completionHandler(lat: lat, long: long, error: nil)
}
}
}

你可以这样调用它:

getCoordinates(string) { lat, long, error in
if error != nil {
// handle the error here
} else {
// use lat, long here
}
}

// but not here

关于iOS Swift 坐标函数返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27769859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com