Bhavesh Odedara
Bhavesh Odedara

Reputation: 79

Convert google direction JSON string url to URL

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

The problem is directionsURL is nil

I know solution is but, In this URL not working

Please help me!

Upvotes: 0

Views: 247

Answers (2)

Ahmad F
Ahmad F

Reputation: 31645

It should be as:

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...
}

the string should be encoded to let it recognizable for the URL.

Also, I would suggest to declare it with optional binding instead of force unwrapping it (URL(string: stringOFDirection)! with an exclamation mark) to make sure that you won't face a crash.

Upvotes: 2

hardik parmar
hardik parmar

Reputation: 853

try adding this before you create the URL: stringOFDirection.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

Upvotes: 5

Related Questions