Modern Concurrency: Getting Started

Oct 18 2022 · Swift 5.5, iOS 15, Xcode 13.4

Part 2: Asynchronous Sequences

11. Using Asynchronous Methods in Views

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Concurrency With async let Next episode: 12. Displaying a Progress View

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Make sure the course server is running and continue with your project from the previous episode or open the starter project for this episode.

SuperStorage app

The download view downloads the file using your choice of subscription plan: silver, gold or Cloud 9.

Download data

In SuperStorageModel, locate download(file:). It already contains the code you know so well:

guard let url = URL(
string: "http://localhost:8080/files/download?\(file.name)") else {
  throw "Could not create the URL."
}
let (data, response) = try await URLSession.shared.data(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
  throw "The server responded with an error."
}
addDownload(name: file.name)
updateDownload(name: file.name, progress: 1.0)
return data

Call download(file:)

Now, where do you call this asynchronous method? Open DownloadView. Go to its body.

fileData = try await model.download(file: file)
let downloadSingleAction: ()  🟩async🟥 -> Void
Task {
  fileData = try await model.download(file: file)
}
@MainActor 
func addDownload(name: String) { ... }
@MainActor 
func updateDownload(name: String, progress: Double) { ... }
.onDisappear {
  fileData = nil
  model.reset()
}