本文介绍了使用Alamofire的同步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经检查了其他解决方案,例如如何使用Alamofire?,我遵循了所有说明,但是我无法完成请求然后使用信息。
I have checked other solutions like How to make a synchronous request using Alamofire?, I followed all instructions but I haven't been able to complete the requests and then use the information.
我需要获取距离和路线从Google地图获取点,然后使用该信息完成一个数组。 这是函数:
I need to retrieve distance and route points from google maps and then complete an array with that information. This is the function:
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 = "maps.googleapis/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 } }如果有人可以帮助我,我将非常感谢。
I'd really appreciate if someone can help me.
推荐答案不要尝试使异步请求同步
Don't try to make an asynchronous request synchronous
在所有网络请求完成后调用 DispatchGroup , notify 代替。
Instead use DispatchGroup,notify is called when all network requests are completed.
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") }更多推荐
使用Alamofire的同步请求
发布评论