URLSessionConfiguration, allowCellularAccess and isDiscretionary
In an earlier blogpost I already briefly covered how to configure an AVAssetDownloadURLSession
and that we can use that to allow/ restrict downloading over cellular. To recap, we do that by instantiating it with URLSessionConfiguration
as following:
let configuration = URLSessionConfiguration.background(withIdentifier identifier: String)
configuration.allowCellularAccess = false
configuration.isDiscretionary = false
configuration.networkServiceType = .video
You will notice that by configuring allowCellularAccess = false
download tasks will not start when the device is not connected to Wi-Fi. Which is great! However this will not automatically stop download tasks which started on Wi-Fi after losing that connection.
Luckily there is a solution for that. URLSessionConfiguration
has another property called isDiscretionary. According to the documentation isDiscretionary
is:
A Boolean value that determines whether background tasks can be scheduled at the discretion of the system for optimal performance.
When set to true
the URLSession will take the value we have set for allowCellularAccess
into consideration to automatically pause and continue active download tasks.
However, there are two important facts considering isDiscretionary
:
- When set to
true
it not only takes our value forallowCellularAccess
into consideration, it also checks the battery-level and wether the device is connected to a charger among other things. Sadly, the documentation is not clear about all the parameters, nor is there a way to influence these. - The state of download tasks will not change when paused due to
isDiscretionary
, which might be slightly confusing.
These drawbacks might be too big for our app to rely on it to pause downloads accordingly. There are ways to do this otherwise, for example by monitoring the connection. Keep in mind that AVAssetDownloadURLSession
is configured as a background session, which will continue downloading when our app is in the background or even suspended. To pause/ resume download tasks with we will have to rely on isDiscretionary
.