Type Safely

Type Safely

Share this post

Type Safely
Type Safely
Download the HTML source from a website

Download the HTML source from a website

Daily Coding Tip 001

Type Safely's avatar
Type Safely
Dec 19, 2020
∙ Paid

Share this post

Type Safely
Type Safely
Download the HTML source from a website
Share
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…

Keep reading with a 7-day free trial

Subscribe to Type Safely to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Type Safely
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share