daniel
daniel

Reputation: 966

Why will this URL not be created from this string in iOS using Swift and Xcode?

Converting String to URL is not working for this string:

https://maps.googleapis.com/maps/api/directions/json?origin=3701%20Moores%20Ln,%20Texarkana,%20TX%2075503,%20USA&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA|5601%20Larry%20Dr,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx

Here is my code:

print(directionsURLString)

let directionsURL = URL(string: directionsURLString)!

Here is the debug window:

https://maps.googleapis.com/maps/api/directions/json?origin=3701%20Moores%20Ln,%20Texarkana,%20TX%2075503,%20USA&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA|5601%20Larry%20Dr,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/shinehah/Documents/Xcode Projects/Routes folder/Routes 08/Routes/MapTasks.swift, line 123
2020-05-29 14:08:52.570189-0500 Routes[1576:2052272] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/shinehah/Documents/Xcode Projects/Routes folder/Routes 08/Routes/MapTasks.swift, line 123

The code worked for this string which has one waypoint, unlike the string that gave an error, which has two waypoints.

https://maps.googleapis.com/maps/api/directions/json?origin=New%20Address&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx

Upvotes: 0

Views: 117

Answers (1)

Gereon
Gereon

Reputation: 17844

The "|" character is the culprit, as it's not in the list of valid characters as per RFC 3986:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=

Solution: replace it with its percent-encoded equvalent, %7c

Upvotes: 1

Related Questions