我正在使用 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/