String To Url and Url To String Swift Tutorial

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts