markhorrocks
markhorrocks

Reputation: 1518

Swift URL appendPathComponent replaces ? with %3F

I have a router which contains the lines

var url = URL(string: MyRouter.baseURLString)!

url.appendPathComponent(relativePath)

This replaces "?" with "%3F" which is rejected by the API server. How can I fix this? It's wrong to encode that character.

Upvotes: 18

Views: 9336

Answers (1)

Code Different
Code Different

Reputation: 93181

Because the ? isn't part of a path. It's a separator to signal the beginning of the query string. You can read about the different components of a URL in this article. Each component has its set of valid characters, anything not in that set needs to be percent-escaped. The best option is to use URLComponents which handles the escaping automatically for you:

var urlComponents = URLComponents(string: MyRouter.baseURLString)!
urlComponents.queryItems = [
    URLQueryItem(name: "username", value: "jsmith"),
    URLQueryItem(name: "password", value: "password")
]

let url = urlComponents.url!

Upvotes: 19

Related Questions