Swift version: 5.6
URLSession
is designed to make network transfers as easy as possible, and a great example of that is its downloadTask
()` method. This fetches the contents of a URL you specify, saves it to a local file, then calls a completion handler so you can manipulate the file – all in one.
To demonstrate this, here’s some code to download the source code to the apple.com homepage:
let url = URL(string: "https://www.apple.com")!
let task = URLSession.shared.downloadTask(with: url) { localURL, urlResponse, error in
if let localURL = localURL {
if let string = try? String(contentsOf: localURL) {
print(string)
}
}
}
task.resume()
There are a few important things to note in there:
resume()
on it to make it happen.URLSession
on your behalf.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 7.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.