Converting URL to String and Back Again in Swift


In Swift, you can convert a URL to a String using the absoluteString property of the URL. To convert a string to a URL, you can use the URL(string:) initializer. In this article, you will see many different examples of how to convert an URL to a string and vice versa.

Example 1: Converting URLs to Strings and Vice Versa

for converting a URL to a string using the absoluteString property and a string to a URL, you can use the URL(string:) initializer. It also mentions that the URL(string:) initializer returns an optional URL value that should be checked for nil.

import Foundation
let url = URL(string: "https://www.example.com")
let urlString = url?.absoluteString
print("URL String: \(String(describing:  urlString))")

Output

URL String: Optional("https://www.example.com")

And this is how to convert a string to a URL

import Foundation
let urlString = "https://www.example.com"
if let url = URL(string: urlString) {
   print("URL Object: \(url)")
} else {
   print("Invalid URL")
}

Output

URL Object: https://www.example.com

Example 2

When converting a URL to a string, the resulting string will include the scheme (e.g. "https://") and any query parameters or fragments. For example,

import Foundation
let url = URL(string: "https://www.example.com/search?q=swift#results")
let urlString = url?.absoluteString
print("URL String: \(String(describing: urlString))")

Output

URL String: Optional("https://www.example.com/search?q=swift#results")

Example 3: Handling Special Characters in URL Strings

If the URL string you're trying to convert contains characters that aren't valid in a URL (such as spaces), you'll need to percent-encode them first using the addingPercentEncoding(withAllowedCharacters:) method. For example −

import Foundation
let urlString = "https://www.example.com/search?q=hello world"
if let encodedString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
   let url = URL(string: encodedString) {
   print("URL Object: \(url)")
} else {
   print("Invalid URL")
}

Output

URL Object: https://www.example.com/search?q=hello%20world

Example 4

If you're working with URLs that include non-ASCII characters (such as accented letters), you should use the URL(string:addingPercentEncodingWithAllowedCharacters:) initializer instead. This will automatically percent-encode any non-ASCII characters in the URL. For example −

import Foundation
let urlString = "https://www.example.com/français"
if let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!,
                 relativeTo: nil) {
   print("URL Object: \(url)")
} else {
   print("Invalid URL")
}

Output

URL Object: https://www.example.com/fran%C3%A7ais

Example 5: Getting the Base URL From a URL String

To get just the base URL (i.e. without the scheme or any query parameters or fragments), you can use the host property of the URL. For example −

import Foundation
let url = URL(string: "https://www.example.com/search?q=swift#results")
let baseUrlString = url?.host
print("Base URL: \(String(describing: baseUrlString))")

Output

Base URL: Optional("www.example.com")

Example 6: Modifying URLs with URLComponents

To modify a URL, you can create a copy of the original URL using the URLComponents struct, modify the desired components (such as the query parameters), and then create a new URL from the modified components. For example −

import Foundation
var urlComponents = URLComponents(string: "https://www.example.com/search")!
urlComponents.queryItems = [
   URLQueryItem(name: "q", value: "swift"),
   URLQueryItem(name: "limit", value: "10")
]
if let url = urlComponents.url {
   print("URL String: \(url.absoluteString)")
} else {
   print("Something is wrong with URL.")
}

Output

URL String: https://www.example.com/search?q=swift&limit=10

Example 7: Handling URLs with non-standard Schemes

If you need to handle URLs with non-standard schemes (such as "tel:" for phone numbers or "mailto:" for email addresses), you can use the canOpenURL(_:) method of the UIApplication class to check whether the device can handle the specified URL scheme, and then use the open(_:) method to open the URL. For example −

import UIKit
let phoneNumber = "+1234567890"
if let url = URL(string: "tel:\(phoneNumber)"), UIApplication.shared.canOpenURL(url) {
   UIApplication.shared.open(url)
} else {
   print("Invalid phone number or unsupported URL scheme")
}

Output

Invalid phone number or unsupported URL scheme

Conclusion

In conclusion, Swift offers a variety of ways to interact with various URL components and to convert between strings and URLs. While the String class has methods for percent-encoding and decoding texts for use in URLs, the URL and URLComponents classes provide a range of attributes and methods that may be used to parse, edit, and construct URLs. Swift's handling of URLs allows you to create strong applications that can interact with online services, show web content, and handle a variety of URL-based functions.

Updated on: 04-May-2023

942 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements