gpt4 book ai didi

swift - 在进行 POST 之前等待找到坐标

转载 作者:行者123 更新时间:2023-11-28 10:40:48 24 4
gpt4 key购买 nike

我正在使用 CLGeocoder 获取用户输入的地址的坐标,该地址将被发送到服务器。但是这个在 POST 到服务器之前调用的函数花费了很长时间,以至于服务器已经发送了信息并且在找到坐标之前已经回复了。我如何等待此函数完成并通知调用它的方法它可以继续?

func getCoordinates(address: String){

let geoCoder = CLGeocoder()

geoCoder.geocodeAddressString(address, completionHandler: { (placemarks, error) in

let placemark = placemarks?.first
self.lat = String(format: "%f",(placemark?.location?.coordinate.latitude)!)
self.lon = String(format: "%f",(placemark?.location?.coordinate.longitude)!)

print("Lat: \(self.lat), Lon: \(self.lon)")
})

}

我查看了 UNUserNotificationCenter 和 DispatchGroup 但没有用...?

最佳答案

有很多方法可以做到这一点。例如你调用Swift Closure检索坐标后。

func getCoordinates(address: String, completionHandler:()->()){

let geoCoder = CLGeocoder()

geoCoder.geocodeAddressString(address, completionHandler: { (placemarks, error) in

let placemark = placemarks?.first
self.lat = String(format: "%f",(placemark?.location?.coordinate.latitude)!)
self.lon = String(format: "%f",(placemark?.location?.coordinate.longitude)!)

print("Lat: \(self.lat), Lon: \(self.lon)")
completionHandler() //call Swift Closure after retrieving coordinates.
})

}

//USAGE
getCoordinates(address: "address",
completionHandler:{
print("Lat: \(self.lat), Lon: \(self.lon)")
//execute POST query here <===
})

关于swift - 在进行 POST 之前等待找到坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50524024/

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