Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Background Downloads

Learn about background tasks and how to use one to handle background events.


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 Professional subscription.

You’ve seen that you can download and upload files, and these transfers are done in a background thread. This means your app can respond to user interface events.

private var session: URLSession
override init() {
  let identifier = "com.razeTunes.mutableSongDownloader"
  let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
  session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
private var session: URLSession!
import UIKit

class AppDelegate: NSObject, UIApplicationDelegate {

@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
class AppDelegate: NSObject, UIApplicationDelegate {
  var backgroundCompletionHandler: (() -> Void)?
func application(
  _ application: UIApplication,
  handleEventsForBackgroundURLSession identifier: String,
  completionHandler: @escaping () -> Void
  ) {
  print("URLSession identifier: \(identifier)")
  backgroundCompletionHandler = completionHandler
static let BackgroundSongDownloadDidFinish = 
NSNotification.Name(rawValue: "BackgroundSongDownloadDidFinish")
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  Task { @MainActor in
    print("urlSessionDidFinishEvents called.")
  Self.BackgroundSongDownloadDidFinish, object: nil)
func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
  ) -> Bool {
                                         selector: #selector(backgroundSongDidDownload),
                                         name: MutableSongDownloader.BackgroundSongDownloadDidFinish,
                                         object: nil)
  return true
@objc private func backgroundSongDidDownload() {
  if let backgroundCompletionHandler = backgroundCompletionHandler {
guard let documentsPath = fileManager.urls(for: .documentDirectory,
                                           in: .userDomainMask).first
else {
  Task {
    await {
      state = .failed
let lastPathComponent = downloadURL?.lastPathComponent ?? "Song.m4a"

Testing Background Downloads

And with that, you’re done and have implemented the ability to perform background downloads. Build and run your app. Tap the download button and background your app.