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
Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Concurrency With async let Next episode: 12. Displaying a Progress View

This video Using Asynchronous Methods in Views was last updated on Oct 18 2022

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

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()
}