使用CLGeocoder获取经纬度时函数返回[0,0]的问题求助
问题原因与解决方案
问题根源
CLGeocoder的geocodeAddressString是异步执行的方法——它会在后台线程完成地理编码操作,操作结束后才会触发传入的闭包。但你的ConvertAddress函数是同步返回结果的,闭包还没来得及给lat和lng赋值,函数就已经返回了初始的[0,0],这就是为什么你拿到的是默认值。
解决方案
方案1:用Completion Handler(兼容iOS 13及更早版本)
修改函数逻辑,不直接返回值,而是通过闭包在编码完成后传递结果:
import CoreLocation func convertAddress(address: String, completion: @escaping ([Double]?, Error?) -> Void) { let geocoder = CLGeocoder() geocoder.geocodeAddressString(address) { placemarks, error in // 先处理错误 if let error = error { completion(nil, error) return } // 提取经纬度 guard let placemark = placemarks?.first, let location = placemark.location else { let noLocationError = NSError(domain: "GeocodingError", code: 0, userInfo: [NSLocalizedDescriptionKey: "未找到对应地点的坐标"]) completion(nil, noLocationError) return } let lat = location.coordinate.latitude let lng = location.coordinate.longitude completion([lat, lng], nil) } } // 调用示例 convertAddress(address: "서원구 수곡로 57번길 32-2(수곡동)") { coordinates, error in if let error = error { print("编码失败:\(error.localizedDescription)") } else if let coords = coordinates { print("获取到经纬度:\(coords)") } }
方案2:用Async/Await(iOS 15+、macOS 12+)
借助Swift的异步语法,让函数变成异步函数,直接返回结果,代码更简洁:
import CoreLocation func convertAddress(address: String) async throws -> [Double] { let geocoder = CLGeocoder() // 异步等待编码结果 let placemarks = try await geocoder.geocodeAddressString(address) // 校验并提取坐标 guard let placemark = placemarks.first, let location = placemark.location else { throw NSError(domain: "GeocodingError", code: 0, userInfo: [NSLocalizedDescriptionKey: "未找到对应地点的坐标"]) } return [location.coordinate.latitude, location.coordinate.longitude] } // 调用示例(需在异步上下文执行,比如Task) Task { do { let coords = try await convertAddress(address: "서원구 수곡로 57번길 32-2(수곡동)") print("获取到经纬度:\(coords)") } catch { print("编码失败:\(error.localizedDescription)") } }
内容的提问来源于stack exchange,提问作者HAN
相关产品推荐
相关产品推荐

