Can not create a Swift URL object including google encrypted polylines

162 Views Asked by At

I am having a validation problem creating an URL object in Swift, returning me nil when I attempt to create it by means of this string:

https://maps.googleapis.com/maps/api/staticmap?size=70x70&path=weight:3%7Ccolor:black%7Cenc:oo%60rG%7Bpxm@zHeW%60H%7BDjJPzKwBnKhKzHrVaExa@gWzCeNsO&path=weight:3%7Ccolor:blue%7Cenc:q|_rG%7Dnym@jJPzKwBnKhKzHrV&key=[my api key]

I need to to use Google Maps Static API in order to get an image of the map including a path I pass as argument to the url in the form of an encrypted polyline.

I tried to escape the url using:

addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)

Doing this let me create an URL object, though the polyline is altered and the path won't be drawn.

Could you please give me any suggestion?

PS. If I type the url I get without applying addingPercentEncoding in the browser, it shows me the image as expected.

PPS. GMS SDK was not included in the project by choice

-- EDIT --

Hi, I tried URLComponents solution suggested by Duncan C, though I got the same result with the google encoded path being distorted.

var urlComponents = URLComponents() 
urlComponents.scheme = "https" 
urlComponents.host = "maps.googleapis.com" 
urlComponents.path = "/maps/api/staticmap"
urlComponents.setQueryItems(with: params)
print(urlComponents.url?.absoluteString) 
if let url = urlComponents.url { // generates wrong url }
1

There are 1 best solutions below

3
Duncan C On

Different parts of a URL need different encoding rules.

I suggest creating your URL using the system class URLComponents. That lets you specify that various parts of a URL (without encoding) and then you query the URLComponents object for the URL.

Edit:

It sounds to me like the problem is in the encoding of your polyline parameters, since you say those are not rendering. You should include a link to the section of the Google documentation on the Google static maps API that deals with encoded polylines, as well as showing your code that encodes your polyline parameters.

A quick Google search on "google maps encoded polyline swift" yielded a project on Github that implements Google's Polyline encoder / decoder in Swift