Beginning Networking with URLSession

Sep 13 2022 · Swift 5.6, iOS 15, Xcode 13.4.1

Part 2: Download Data

14. Show Download Progress

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: 13. Challenge: Download Images Next episode: 15. Grouping Requests

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.

Notes: 14. Show Download Progress

URLSession - Apple Developer

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

When downloading images or large over the network, the user will often times want to know the progress of the total download. If using the closure-based task downloads on URLSession, you have delegate methods for this.

@MainActor @State private var downloadProgress: Float = 0.0
if isDownloading {
  ProgressView(value: downloadProgress)
}
func downloadSongBytes(at url: URL, progress: Binding<Float>) async throws {
    
}
try await downloader.downloadSongBytes(at: previewURL, progress: $downloadProgress)
let (asyncBytes, response) = try await session.bytes(from: url)
let contentLength = Float(response.expectedContentLength)
var data = Data(capacity: Int(contentLength)) 
for try await byte in asyncBytes {
 
}
data.append(byte)
progress.wrappedValue = Float(data.count) / Float(contentLength)
let currentProgress = Float(data.count) / contentLength
if Int(progress.wrappedValue * 100) != Int(currentProgress * 100) {
  progress.wrappedValue = currentProgress
}
let fileManager = FileManager.default

guard let documentsPath = fileManager.urls(for: .documentDirectory,
                                           in: .userDomainMask).first
else {
  throw SongDownloadError.documentDirectoryError
}
let lastPathComponent = url.lastPathComponent
let destinationURL = documentsPath.appendingPathComponent(lastPathComponent)
do {
  if fileManager.fileExists(atPath: destinationURL.path) {
    try fileManager.removeItem(at: destinationURL)
  }
    
  try data.write(to: destinationURL)
} catch {
 throw SongDownloadError.failedToStoreSong
}
await MainActor.run {
  downloadLocation = destinationURL
}