gpt4 book ai didi

swift - 使用 Alamofire 的同步请求

转载 作者:搜寻专家 更新时间:2023-11-01 06:27:35 25 4
gpt4 key购买 nike

我检查了其他解决方案,例如 How to make a synchronous request using Alamofire? ,我遵循了所有说明,但我无法完成请求然后使用信息。

我需要从谷歌地图中检索距离和路线点,然后用这些信息完成一个数组。这是函数:

func getGoogleMapsInfo(startLocation: CLLocationCoordinate2D, restaurant: Customer, completion: @escaping (_ distance: Int, _ routePoints: String)  -> ()){

let endLocation = CLLocationCoordinate2D(latitude: restaurant.latitude, longitude: restaurant.longitude)
let origin = "\(startLocation.latitude),\(startLocation.longitude)"
let destination = "\(endLocation.latitude),\(endLocation.longitude)"
var distance = 0
var routePoints = ""

let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=walking"
Alamofire.request(url).responseJSON { response in

switch response.result {
case .success:

do {
self.json = try JSON(data: response.data!)

distance = Int(truncating: self.json["routes"][0]["legs"][0]["distance"]["value"].numberValue)


let route = self.json["routes"].arrayValue.first
let routeOverviewPolyline = route!["overview_polyline"].dictionary
routePoints = (routeOverviewPolyline?["points"]?.stringValue)!
completion(distance, routePoints)
break
} catch {
print("error JSON")
}


case .failure(let error):
print(error)
completion(distance, routePoints)
break
}

}


}

我是这样调用它的:

    for index in 0...nearbyRestaurants.count - 1 {

getGoogleMapsInfo(startLocation: currentLocation, restaurant: nearbyRestaurants[index]) { (distance, routePoints) in
nearbyRestaurants[index].distance = distance
nearbyRestaurants[index].routePoints = routePoints
}

}

如果有人能帮助我,我将不胜感激。

最佳答案

不要试图使异步请求同步

改为使用DispatchGroup,当所有网络请求完成时调用notify

let group = DispatchGroup()
for index in 0..<nearbyRestaurants.count {
group.enter()
getGoogleMapsInfo(startLocation: currentLocation, restaurant: nearbyRestaurants[index]) { (distance, routePoints) in
nearbyRestaurants[index].distance = distance
nearbyRestaurants[index].routePoints = routePoints
group.leave()
}
}
group.notify(queue: DispatchQueue.main) {
print("all info data has been received")
}

关于swift - 使用 Alamofire 的同步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51899792/

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