将Google方向JSON字符串网址转换为网址

时间:2017-11-02 07:28:57

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

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)!

问题是directionsURL为零

我知道解决方案但是,在此网址中无效

请帮助我!

2 个答案:

答案 0 :(得分:5)

尝试在创建网址之前添加此内容: <img id='play' src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNCIgaGVpZ2h0PSIxOCIgdmlld0JveD0iMCAwIDEyMjYgMTQ4MSI+CiAgPHBhdGggZD0iTTAgMTM5NFY4N0MwIDQ2LjMgMTMuMyAxOS44IDQwIDcuNSA2Ni43LTQuOCA5OC43LjMgMTM2IDIzbDEwMzQgNjM0YzM3LjMgMjIuNyA1NiA1MC4zIDU2IDgzcy0xOC43IDYwLjMtNTYgODNMMTM2IDE0NThjLTM3LjMgMjIuNy02OS4zIDI3LjgtOTYgMTUuNS0yNi43LTEyLjMtNDAtMzguOC00MC03OS41eiIgZmlsbD0iIzAwNTlkZCIvPgogPC9zdmc+'> <div id='time'></div>

答案 1 :(得分: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)!带有感叹号),以确保你不会遇到崩溃。< / p>