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 In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.
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.