Resilient large downloads

Networking Senior Swift 5.5+ iOS 16+ Reviewed By Alok Singh

Pick the fix

In urlSession(_:downloadTask:didFinishDownloadingTo:), what must you do with the location URL?

Options
Hint 1 of 1

How long does the temporary file exist?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Move the file to a permanent location before the method returns

Correct. The system deletes the temporary file afterwards.

Why not the others?
  • B Save the URL and move the file later on the main queue. By then the temporary file is gone.
  • C Read the whole file into Data and save it. Reading 2 GB into memory gets the app killed.
  • D Leave it in the temporary directory. It will be deleted.

30-second answer

Use a background URLSession download task so the transfer continues when the app is suspended or terminated. Move the file to permanent storage inside didFinishDownloadingTo before the method returns, because the temporary file is then deleted. Save resume data on failure, check free space first, verify a checksum, and show progress per item.

Practise saying it · 60 s. No recording, just a timer

Design a resilient large download.

Say your answer out loud, then check which of these points you covered:

  • Background session
  • Move file synchronously
  • Resume data
  • Checksum and progress

Deep dive

Split large content into chunks or items so one failure doesn't restart everything.

Handle application(_:handleEventsForBackgroundURLSession:completionHandler:) to finish after relaunch.

Mark large re-downloadable files as excluded from backup.

Respect Low Data Mode and cellular settings.

Common mistakes

  • Moving the file asynchronously after the delegate returns.
  • Loading the whole file into memory as Data.

Senior take & follow-ups

Seniors cover the system handoff, file handling, verification and user communication.

Follow-up questions

Think of your answer first, then open the hint.

  1. What is resume data?

    Show hint

    A blob from the failed task that resumes from the last byte, if the server supports ranges.

  2. Why exclude from backup?

    Show hint

    It can be downloaded again and would fill the user's iCloud.

Suggest a fix if something here is wrong or out of date.