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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With