Reputation: 4891
I have created a class to download file using URLSession
.
I noticed a weird behavior that when device in debug mode, it is downloading files. But if I remove device and run app manually, downloading is not working at all. Sometimes re-attaching device starts the download.
This is how I am creating URLSession :
private lazy var urlSession: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "org.company.id")
config.isDiscretionary = true
config.sessionSendsLaunchEvents = true
config.allowsCellularAccess = true
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
And here is my request download function :
func requestDownload(urlString: String){
guard let url = URL(string: urlString) else {return}
downloadTask = urlSession.downloadTask(with: url)
downloadTask.taskDescription = urlString
downloadTask.resume()
}
Here is a link to that file downloader class : https://github.com/skdevil/PrakrstaFileDownloader
Any idea how to fix it ?
Upvotes: 2
Views: 915
Reputation: 437442
The issue is that when you run it attached to your debugger, the app is never suspended, whereas on a device can be.
A couple of observations:
It is possible you have not implemented handleEventsForBackgroundURLSession
in your app delegate or urlSessionDidFinishEvents(forBackgroundURLSession:)
in your URLSessionDelegate
. They're required for background downloads. We'd need to see those implementations to comment further.
For more information see Downloading Files in the Background.
FYI, I've issued a pull request on that repo, showing what you need to do to support background sessions.
Or, if you've done all of that correctly, note that you've set discretionary mode. This means that it will download when attached to power and wifi. Is that the case?
Note, I'd encourage doing some logging so you can see what's going on. But you cannot use Xcode's debugging mechanisms for this (because, as you've noticed, being attached to Xcode changes the behavior of the app).
You can, instead, log using "unified logging" as outlined in WWDC 2016 video Unified Logging and Activity Tracing. That way, you can watch log messages from your iOS device on your macOS console, and you don't have to write your own file logging system. See point 3 at https://stackoverflow.com/a/25951564/1271826 for example of how to observe iOS log messages on macOS console. Or see that aforementioned WWDC video.
Upvotes: 4