如何侦听来自其他功能的代表响应?
问题描述:
我想要一个名为requestData的函数,它将获取用户的当前位置,然后执行URL请求。我需要requestData函数在请求完成时有回调,不管它是否成功。这是我想出迄今:如何侦听来自其他功能的代表响应?
requestData(_ completion:@escaping()->()){
self.locationManager.requestLocation()
// Wait for the location to be updated
let location:CLLocation? = //myLocation
self.performRequest(with: location, completion: completion)
}
func performRequest(with location:CLLocation?, completion:@escaping()->()){
//Does the URL-request, and simply calls completion() when finished.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {//Success}
else{//Error}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{//Error}
我的想法是调用的RequestData,它将请求myLocation,然后调用performRequest。但CLLocationManager使用委托回调而不是块来执行requestLocation
。我应该怎么做? 一切会一直很大,如果requestLocation会一直是这样的:
self.locationManager.requestLocation({ (locations, error) in
if locations {}
else {}
})
但它不是..
为了澄清,这是一个小部件(TodayExtension)的代码,其中,按照我的理解,需要回调,因为我需要widgetPerformUpdate(completionHandler:)
在触发它自己之前等待我自己的completionHandler。
答
CLLocation包含几个数据来检查您获得的位置的准确性和时间。对于您来说,解决方案可能是在执行请求执行请求()之前检查此数据的准确性。
查看CLLocation的文档,看看我下面的伪代码。在didUpdateLocations
中,您可以了解我认为可能是您的解决方案。我直接在SO中编写它,所以不要憎恨错误。
但基本上使用:
VAR horizontalAccuracy:CLLocationAccuracy {得到}
VAR verticalAccuracy:CLLocationAccuracy {得到}
VAR时间戳:日期{得到}
let location:CLLocation? //myLocation
func requestData(){
self.locationManager.requestLocation()
// Wait for the location to be updated
}
func performRequest(with location:CLLocation?, completion:@escaping()- >()){
//Does the URL-request, and simply calls completion() when finished.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
//When the location is accurate enough we can call
//the performRequest()
if location.horizontalAccuracy < 15 && location.timestamp > (Date().timestampSince1970 - 60){
//Accurate enough?? Then do the request
self.performRequest(with: location, completion: completion)
}else{
//Not accurate enough...wait to the next location update
}
}
else{//Error}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{//Error}
您可以使用CLLocation并检查该位置的时间和准确性在调用performRequest()之前获得。这样你就知道这个位置是尽可能准确和更新的。 – Starlord
您可以将回调处理程序保存在属性中,然后从委托方法调用它 – Paulw11