Let’s learn how to convert Strings to URLs and back.
To create a url from a string, simply call the URL constructor:
let url = URL(string: "https://www.zerotoappstore.com/")
To convert a URL to a string, call .absoluteString
:
let url = URL(string: "https://www.zerotoappstore.com/")
let urlString = url.absoluteString
You’ll often have to format a URL with parameters when calling an API. This parameters can change based on the state of your application or based on user input.
You can solve this problem by using strings and creating URLs from them. For example:
func findSomething(query: String) {
let api = "https://api.zerotoappstore.com"
let endpoint = "/search?q=\(query)"
let url = URL(string: api + endpoint)
...
}
However, this will quickly become complicated and hard to read when there are a lot of parameters.
A better way to construct URLs that have a lot of parameters is to use URLComponents
:
func findSomething(query: String,
number: Int) {
var components = URLComponents()
components.scheme = "https"
components.host = "api.zerotoappstore.com"
components.path = "/search"
components.queryItems = [
URLQueryItem(name: "q", value: query),
URLQueryItem(name: "number", value: number)
]
let url = components.url
}
With URLComponents
you can add as many query items as you need in a clean, readable manner. It also allows you to see the scheme, host and path easily.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.