等待在发布POST之前找到坐标

时间:2018-05-25 07:44:54

标签: swift wait

我正在使用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,但无济于事......?

1 个答案:

答案 0 :(得分:3)

有很多方法可以做到这一点。例如,您在检索坐标后调用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 <===
})