I am creating a background session using this code...
let configuration = URLSessionConfiguration.background(withIdentifier: UUID().uuidString)
configuration.sessionSendsLaunchEvents = true
configuration.isDiscretionary = false
self.session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
...and download tasks using this code:
let downloadTask = self.session.downloadTask(with: request as URLRequest)
downloadTask.resume()
My request objects looks like this:
let request = NSMutableURLRequest(url: someURL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do {
try request.httpBody = JSONSerialization.data(withJSONObject: someDictionary, options: JSONSerialization.WritingOptions())
} catch let error as NSError {
// logging calls
}
The resources being download are ~20MB zip files.
I can run four concurrent downloads in the foreground with no issue. All expected delegate methods are called and the transfers complete at a normal speed.
The problem that I am seeing is that if I start the downloads in the foreground and then hit the home button the downloads will sometimes stall. I have tried keeping the device awake and the network spun up for an hour and the transfers still don't complete in the background. Additionally, when I bring the app back to the foreground the transfers do not immediately start again. If I let the app sit in the foreground for ~4 minutes, they will wake up and start working again. They resume at the percentage complete they were at when the app went into the background, and will transfer at normal speed until complete. At no time are there any errors, and the transfer is ultimately successful. It just "goes away" while in the background, and is very slow to resume when the app comes back to the foreground.
I am testing on an iPhone 6 running iOS 10. I am not connected to Xcode or external power and I am launching the app cold. I can reproduce the issue over both WiFi and cellular connections. I have deleted the app and reloaded it multiple times.
I am having trouble tracking this down because approximately 20% of the time it works fine. I have not found any particular set of variables that causes it to consistenly work or fail. It seems to happen more frequently when multiple downloads are occuring, and in that situation all of the downloads exhibit the behavior described above.
Any guidance would be greatly appreciated!
Matt