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

Boost your skills with a raywenderlich.com 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.

Contributors

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 raywenderlich.com 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() {
  super.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.")
      
    NotificationCenter.default.post(name: Self.BackgroundSongDownloadDidFinish, object: nil)
  }
}
func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
  ) -> Bool {
  NotificationCenter.default.addObserver(self,
                                         selector: #selector(backgroundSongDidDownload),
                                         name: MutableSongDownloader.BackgroundSongDownloadDidFinish,
                                         object: nil)
    
  return true
}
@objc private func backgroundSongDidDownload() {
  if let backgroundCompletionHandler = backgroundCompletionHandler {
    backgroundCompletionHandler()
  }
}
guard let documentsPath = fileManager.urls(for: .documentDirectory,
                                           in: .userDomainMask).first
else {
  Task {
    await MainActor.run {
      state = .failed
  }
}
  
  return
}
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.

Reviews

Comments