17

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.

markhorrocks
  • 1,199
  • 19
  • 82
  • 151
  • It's wrong to include "?" into the path components. It is used as a separator between path and query, so it NEEDS to be percent-encoded if you really want it in the path. If you want to create a URL with query, like `https://example.com?name=value`, you may try to use `URLComponents` or just use string concatenation. – OOPer Apr 26 '17 at 21:04
  • I changed it to use string concatenation. The relative path was in the form /search?since=1 – markhorrocks Apr 26 '17 at 21:20
  • Have you successfully made it? If you find some difficulty still now, please edit your question and add some details about it. – OOPer Apr 26 '17 at 22:17
  • you need to create string of your url and set URLEncoding like https://stackoverflow.com/a/51894621/3110023 – iman Aug 17 '18 at 11:44

1 Answers1

18

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!
Code Different
  • 90,614
  • 16
  • 144
  • 163