【问题标题】:Convert google direction JSON string url to URL将 google 方向 JSON 字符串 url 转换为 URL
【发布时间】:2017-11-02 07:28:56
【问题描述】:
let stringOFDirection: String = "https://maps.googleapis.com/maps/api/directions/json?origin=23.0723857839751,72.5160750795044&destination=23.057534,72.577191&waypoints=optimize:true|23.0557874,72.465833"

let directionsURL = URL(string: stringOFDirection)!

问题是方向URL为nil

我知道解决方案是,但是在这个 URL 中不起作用

请帮帮我!

【问题讨论】:

  • 尝试用%2C替换逗号
  • “|”的问题字符,在 URL 中是非法的。
  • 我认为| 是问题所在,至少没有它它也能工作,用%7C 替换它应该可以解决问题,但它不是很动态。
  • 不工作.... #Callam

标签: ios json swift google-maps-sdk-ios swift4


【解决方案1】:

在创建 URL 之前尝试添加:stringOFDirection.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

【讨论】:

  • 别忘了安全地打开它。并接受正确的答案。
【解决方案2】:

应该是这样的:

let stringOFDirection: String = "https://maps.googleapis.com/maps/api/directions/json?origin=23.0723857839751,72.5160750795044&destination=23.057534,72.577191&waypoints=optimize:true|23.0557874,72.465833"

if let encodedStringOFDirection = stringOFDirection.addingPercentEncoding(withAllowedCharacters: . urlQueryAllowed), let directionsURL = URL(string: encodedStringOFDirection) {
    print(encodedStringOFDirection)

    // directionsURL is not nil and it works as expected...
}

应该对字符串进行编码以使其可被 URL 识别。

另外,我建议使用 可选绑定 来声明它,而不是强制解包(URL(string: stringOFDirection)! 带有感叹号),以确保您不会遇到崩溃。

【讨论】:

  • 很高兴为您提供帮助。不要忘记接受答案(绿色勾选):) 仅供参考,接受答案会导致: - 给予回答者 +15 声望点。 - 给你(询问者)+2 声望点。 - 最重要的是,它向观众表明此答案是解决此问题的适当解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多