Swift version: 5.6
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 Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.
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.