Beginning Networking with URLSession

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

Part 2: Download Data

12. Handle Errors

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: 11. Download Music Next episode: 13. Challenge: Download Images

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: 12. Handle Errors

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

Errors happen all the time, especially when working with networks. There are two levels of errors to think about when working with URL requests: 1. Thrown errors from the functions themselves. 2. Non-successful HTTP status codes.

func downloadSong(at url: URL) async throws {   // THIS IS NEW!
  …
}
class SongDownloader: ObservableObject {
  // MARK: Song Download Error
  enum SongDownloadError: Error {
    case invalidResponse
  }

  …
}
let (downloadURL, response) = try await session.download(from: url)
throw SongDownloadError.invalidResponse
enum SongDownloadError: Error {
  case documentDirectoryError       // THIS IS NEW!
  case invalidResponse
}
guard let documentsPath = fileManager.urls(for: .documentDirectory,
                                           in: .userDomainMask).first
else {
  throw SongDownloadError.documentDirectoryError    // THIS IS NEW!
}
enum SongDownloadError: Error {
  case documentDirectoryError
  case failedToStoreSong        // THIS IS NEW!
  case invalidResponse
}
do {
  if fileManager.fileExists(atPath: destinationURL.path) {
    try fileManager.removeItem(at: destinationURL)
  }
        
  try fileManager.copyItem(at: downloadURL, to: destinationURL)
} catch {
  throw SongDownloadError.failedToStoreSong     // THIS IS NEW!
}
@MainActor @State private var showDownloadFailedAlert: Bool = false
do {
  try await downloader.downloadSong(at: previewURL)
} catch let error {
  print(error)

  showDownloadFailedAlert = true
}
Button(action: {
  Task {
    await downloadTapped()
  }
}) {
  if isDownloading {
    Text("Downloading...")
  } else {
    Text(downloader.downloadLocation == nil ? "Download" : "Listen")
  }
}   
    // THIS IS NEW!!!!
.alert("Download Failed", isPresented: $showDownloadFailedAlert) {
  Button("Dismiss", role: .cancel) {
        showDownloadFailedAlert = false
    }
}
.disabled(isDownloading)