使用 Alamofire 的同步请求
Posted
技术标签:
【中文标题】使用 Alamofire 的同步请求【英文标题】:Synchronous request using Alamofire 【发布时间】:2018-08-17 16:45:59 【问题描述】:我检查了其他解决方案,例如 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
如果有人可以帮助我,我将不胜感激。
【问题讨论】:
"检查了其他解决方案,例如如何使用 Alamofire 发出同步请求?"不要检查它们。永远永远永远永远不会同步网络。绝不。我有没有提到过? @matt 同步网络请求可以来自后台线程。 @Cristik 我有没有提到“除非你已经在后台线程上”? @matt 我可能在某处看到过 :) 【参考方案1】:不要尝试使异步请求同步
改为使用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")
【讨论】:
以上是关于使用 Alamofire 的同步请求的主要内容,如果未能解决你的问题,请参考以下文章
如何正确使用信号灯同步 Alamofire 请求 Swift4 的主线程?