使用Alamofire的同步请求

编程入门 行业动态 更新时间:2024-10-26 04:20:16
本文介绍了使用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的同步请求

本文发布于:2023-11-26 03:26:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632447.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Alamofire

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!