Type Safely

Type Safely

Download the HTML source from a website

Daily Coding Tip 001

Type Safely's avatar
Type Safely
Dec 19, 2020
∙ Paid
Image by James Osborne from Pixabay

Here’s how to get the underlying HTML from a webpage.

import Foundation
func getHTMLSource() -> String {
//Create the URL
guard let url = URL(string: "https://apple.com") else {
fatalError("Could not create URL")
}
// Try downloading the HTML source
do {
return try String(contentsOf: url, encoding: .utf8)
}
//If there is an error
catch let error {
fatalError("Failed to download HTML due to error: \(error.localizedDescription)")
}
}
view raw getHTMLSource.swift hosted with ❤ by GitHub

Creating the source URL

I’m using the Apple website in my example, but you can use whatever you want. If you’re unfamiliar with guard let, this is allowing us to optionally bind the result of an optional initialiser. URL can fail and return nil, depending on whether t…

User's avatar

Continue reading this post for free, courtesy of Type Safely.

Or purchase a paid subscription.
© 2026 Type Safely · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for great culture