等待找到坐标再制作POST
Waiting for coordinates to be found before making POST
我正在使用 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 <===
})
我正在使用 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 <===
})