String To Url and Url To String Swift Tutorial

Let’s learn how to convert Strings to URLs and back.

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)
    ...
}

However, this will quickly become complicated and hard to read when there are a lot of parameters.

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
}

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.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts