Download the HTML source from a website
Daily Coding Tip 001

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

