Creating a URL from a String
To create a url from a string, simply call the URL constructor:
let url = URL(string: "https://www.zerotoappstore.com/")
Get String From URL
To convert a URL to a string, call .absoluteString:
let url = URL(string: "https://www.zerotoappstore.com/")
let urlString = url.absoluteString
Format URL With Parameters
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)
...
}
URL Components
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
}