Swift version: 5.10
It takes just a few lines of Swift code to load the contents of a website URL, but there are three things you need to be careful with:
URL
might fail if you pass a bad site, so you need to unwrap its optional return value.do/catch
block.Here's the code:
if let url = URL(string: "https://www.hackingwithswift.com") {
do {
let contents = try String(contentsOf: url)
print(contents)
} catch {
// contents could not be loaded
}
} else {
// the URL was bad!
}
If you want to run that on a background thread (and you really ought to!) you should either use GCD's async()
or performSelector(inBackground:)
.
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 2.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.