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:)
.
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
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.