Advanced Networking with URLSession

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

Part 1: Upload Data, Background Downloads & WebSockets

04. Background Downloads

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: 03. Upload Data Next episode: 05. Understand Sockets

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: 04. Background Downloads

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

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.