AVAssetDownloadURLSession

When Downloading HLS, you can not use URLSession.shared. Instead, you will need to set up a dedicated URLSession. AVFoundation offers a specialised subclass of URLSession, tailored for downloading HLS: AVAssetDownloadURLSession.

To create an instance of AVAssetDownloadURLSession, you will need to provide an URLSessionConfiguration, AVAssetDownloadDelegate and OperationQueue as following:

AVAssetDownloadURLSession(configuration: URLSessionConfiguration,
                          assetDownloadDelegate: AVAssetDownloadDelegate?,
                          delegateQueue: OperationQueue?)

Keep in mind that, even though assetDownloadDelegate is an optional parameter, you will need to pass a delegate to handle your HLS downloads properly.

URLSessionConfiguration

An instance of URLSessionConfiguration is used to determine the behaviour of the URLSession. After creating the configuration you can tailor it to your needs. For example, you can use it to allow downloading over cellular or determine a network service type. Creating a typical configuration for AVAssetDownloadURLSession will look something like this:

let identifier = "hlsURLSessionIdentifier"
let configuration = URLSessionConfiguration.background(withIdentifier: identifier)

configuration.allowCellularAccess = false
configuration.networkServiceType = .video

The configuration must be setup as a background URLSessionConfiguration, or an exception will be raised.

Key characteristics of a background URLSession

An URLSession configured with a background URLSessionConfiguration is meant for long-running and nonurgent downloads, of which the device takes control of executing them and the device informs you through delegate callbacks.

The biggest benefits of this setup are:

For more in-depth information about downloading in the background using a background URLSessionConfiguration, I suggest checking out Appleā€™s documentation on this topic.