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 Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.
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.