swift - 使用 Alamofire 的同步请求

标签 swift alamofire

我检查了其他解决方案,例如 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/

相关文章:

ios - 从 Swift 中的背景颜色确定文本颜色?

swift - 我可以设置图像的顺序吗? PHPickerViewController

ios - 打印出结果后执行 Alamofire 请求

swift - 我如何查看 Alamofire 请求?

swift - 如何在运行时将 StaticString 转换为 String?

ios - swift : Data passed through unwind segue is erased before being read

arrays - 使用嵌套的 decended 枚举案例作为父枚举案例

swift - Alamofire 库不响应 Swift 包管理器

ios - 正确使用 Alamofire 路由器

swift - 尝试在一次调用中从 Web 服务获取所有数据