Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift URL appendPathComponent replaces ? with %3F

Tags:

swift

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.

like image 502
markhorrocks Avatar asked Apr 26 '17 20:04

markhorrocks


People also ask

What is foundation URL?

URL is one of the most common types used by Foundation for File IO as well as network-related tasks. The goal of this proposal is to improve the ergonomics of URL by introducing some convenience methods and renaming some verbose/confusing ones.

What is swift URL?

URLs in Swift are used in a lot of ways. We fetch data using an API, images to visualize our app, and we often work with local files from our bundle. The Foundation framework allows us to access a lot of URL components easily with default parameters.


1 Answers

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!
like image 164
Code Different Avatar answered Sep 21 '22 06:09

Code Different