gpt4 book ai didi

json - Google Directions Api URL 返回 nil

转载 作者:行者123 更新时间:2023-11-28 06:00:52 25 4
gpt4 key购买 nike

我正在尝试使用 Google directions api 获取路线。到目前为止我所做的一切都有效。我有搜索功能,可以保存搜索到的位置(使用谷歌的建议位置),然后在那里放置一个标记。

我刚刚添加了一些代码,这些代码将使用 Google Directions API 从特定位置(在本例中为我的当前位置)绘制 map 。我的应用程序跟踪我的位置和一切都没有问题。

当我尝试创建 URL 时,我的 guard 语句中不断出现“错误:无法创建 URL”错误,我在下面附上了屏幕截图,但我还是有点困惑。它说 key= 那就是我输入我的 API key 的地方。我显然没有在这个屏幕截图中包含它,因为这会让每个人都可以访问我的 API key 。

我继续并实际使用打印的 urlString(显示在控制台中)并将 URL 复制到我的网页并且它完美地工作。它显示了我想要它显示的内容(据我所知),甚至在网页中没有 key 的情况下进行了尝试,它仍然有效。有人遇到过这个问题吗?我已经执行了传输安全域异常(exception),所以那里没有问题。

我附上了下面的代码。 currentLatitude/Longtitude 和 searchedLatitude/Longitude 都是 CLLocationDegrees 类型。 Current 是我当前的位置坐标,searched 是用户搜索位置时返回给我的坐标

    let currLat = String(currentLatitude)
let currLong = String(currentLongitude)

let seLat = String(searchedLatitude)
let seLong = String(searchedLongitude)

let originCoordinateString = "\(currLat), \(currLong)"
let destinationCoordinateString = "\(seLat), \(seLong)"
print(currentLatitude)
print(currentLongitude)
print(searchedLatitude)
print(searchedLongitude)
let urlString = "http://maps.googleapis.com/maps/api/directions/json?origin=\(originCoordinateString)&destination=\(destinationCoordinateString)&sensor=false"

print(urlString)

guard let url = URL(string: urlString) else {
print(urlString)
print ("Error: cannot create URL")
return
}

最佳答案

原因

url = URL(string: urlString)

失败是因为 urlString 包含空格。

从技术上讲,URL 的格式具有严格的标准。

浏览器按原样接受它,因为它会在发送前自动修复它。

在您的情况下,您只需删除 originCoordinateStringdestinationCoordinateString 变量中的空格即可。

  • 蠢货。

关于json - Google Directions Api URL 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49807760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com