使用Alamofire的同步请求

时间:2018-08-17 16:46:00

标签: swift alamofire

我检查了诸如How to make a synchronous request using Alamofire?之类的其他解决方案,按照所有说明进行操作,但无法完成请求,然后使用信息。

我需要从Google地图检索距离和路线点,然后使用该信息完成一个数组。 这是功能:

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
        }

    } 

如果有人能帮助我,我将非常感谢。

1 个答案:

答案 0 :(得分:3)

不要尝试使异步请求同步

代替使用DispatchGroupnotify在所有网络请求完成后被调用。

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")
}