ios - 使用 swift 和 alamofire 的 url 谷歌地图方向 api 与航点无效

标签 ios swift google-maps alamofire google-directions-api

我正在尝试使用谷歌地图方向 API 在谷歌地图上绘制点列表的方向,我使用 alamofire 进行网络请求,当我尝试使用浏览器获取响应 JSON 数据时,它可以工作很好,它返回所需的数据,但是当我使用 alamofire 请求时,我收到此响应错误:

URL is not valid

这是我的代码:

        let headers: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]

        let url = "https://maps.googleapis.com/maps/api/directions/json?origin= 33.85735529390786,35.48763965724007&destination=33.86317291423991,35.49212425947189&mode=driving&waypoints=|21.4276001,39.2765001|21.4025001,39.2744001|21.7728001,39.1931001|21.7081001,39.1044001&key=myKey"

          Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in

                    print(response.request as Any)  // original URL request
                    print(response.response as Any) // HTTP URL response
                    print(response.data as Any)     // server data
                    print(response.result as Any)   // result of response serialization
                    do{
                        let json = try JSON(data: response.data!)
                        let routes = json["routes"].arrayValue

                        // print route using Polyline
                        for route in routes{
                            let routeOverviewPolyline = route["overview_polyline"].dictionary
                            let points = routeOverviewPolyline?["points"]?.stringValue
                            let path = GMSPath.init(fromEncodedPath: points!)
                            let polyline = GMSPolyline.init(path: path)
                            polyline.strokeWidth = 4
                            polyline.strokeColor = UIColor.blue
                            polyline.map = self.mapView
                        }
                    }catch let error {
   print(error.localizedDescription)
                    }


                }

提前致谢。

最佳答案

您需要添加addingPercentEncoding

  var url = "https://maps.googleapis.com/maps/api/directions/json?origin= 33.85735529390786,35.48763965724007&destination=33.86317291423991,35.49212425947189&mode=driving&|21.4276001,39.2765001|21.4025001,39.2744001|21.7728001,39.1931001|21.7081001,39.1044001&key=myKey"

  url = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

关于ios - 使用 swift 和 alamofire 的 url 谷歌地图方向 api 与航点无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56039137/

相关文章:

javascript - 如何在 Google map API 上的标记周围添加圆圈

ios - 快速将单元格并排放置在 Collection View 中

objective-c - 在使用额外行插入新记录的同时在编辑模式之间切换时如何使用核心数据并正确显示动画?

ios - 如何保存关系数据(核心数据)

swift - xcode 数组中图像的圆角

ios - 如何将数据从 TabBarController View 之一传递到非 TabBarController View ?

android - Android 手机标配 Google map ?