How can I encode a URL to pass Percent (%) sign in Swift?

Viewed 197

I need a URL like this to work:

https://somehost.gov/api/wtk_download.csv?api_key=DEMO_KEY&wkt=POINT(-104.23828125%252039.90973623454)&attributes=power&names=2009&interval=60&full_name=SampleUser&email=sample@email.com&affiliation=TestOrganization&reason=Dev

Code I used to generate the URL:

let wktStr: String = "POINT("+formattedX+"%"+formattedY+")"
var components = URLComponents()
components.scheme = "https"
components.host = "somehost.gov"
components.path = "/api/wtk_download.csv"
components.queryItems = [
    URLQueryItem(name: "api_key", value: "DEMO_KEY"),
    URLQueryItem(name: "wkt", value: wktStr),
    URLQueryItem(name: "attributes", value: "power"),
    URLQueryItem(name: "names", value: yearString),
    URLQueryItem(name: "interval", value: "60"),
    URLQueryItem(name: "full_name", value: "SampleUser"),
    URLQueryItem(name: "email", value: "sample@email.com"),
    URLQueryItem(name: "affiliation", value: "TestOrganization"),
    URLQueryItem(name: "reason", value: "Dev")

]

let url = components.url
print(url!)
print(url!.absoluteURL)

Prints:

https://somehost.gov/api/wtk_download.csv?api_key=DEMO_KEY&wkt=POINT(-104.23828125%252039.90973623454)&attributes=power&names=2009&interval=60&full_name=SampleUser&email=sample@email.com&affiliation=TestOrganization&reason=Dev

The server host gives an error because the POINT(-104.23828125%252039.90973623454) has %25 instead of just %.

How can I generate the item POINT(-104.23828125%2039.90973623454) which has just the %?

1 Answers

Looks like you're trying to use the Wind Toolkit Data API.

In one of their example requests, they have a query parameter that they show looks like this:

wkt=POINT(-104.23828125%2039.90973623453719)

That %20 is really just a URL-encoded space character.

(It is kind of confusing how they show a URL-encoded value for the wkt parameter, but not for other parameters whose values contain spaces like full_name=Sample User or affiliation=Test Organization, so it's understandable where the confusion comes from.)

Anyway, to fix the problem, just replace the % character in your wktStr with a space:

let wktStr: String = "POINT("+formattedX+" "+formattedY+")"
Related