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 Join some of the App Store’s biggest apps—from brands like Mojo and Citizen to thriving indies. Test pricing, run paywall experiments, update locked features, and now, launch web checkout links straight from your app—all without updates. Superwall is your complete growth toolkit.
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.