I'm trying to download using urlsession background session this is my main function
func startfresh() {
session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue())
let url = URL(string: "https://nava.ir/wp-content/uploads/2018/08/Gholamreza-Sanatgar-Dorooghe-Sefid-128.mp3")
task = session.downloadTask(with: url!)
task.resume()
}
and my didcompletewitherror
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error != nil {
let err = error as NSError?
let resumeData = err?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
print("anotherone")
let newtask = session.downloadTask(withResumeData: resumeData!)
newtask.resume()
}
else {
print("hichi")
}
}
but when I close the app when the download is still on progress and relaunch it again and press start download it starts 2 tasks resume previous one and start a new one I want to just resume the previous one with resume data what should I do to just trigger did complete with error method.
What you are seeing is kind of "expected" and you have to design your software to handle it. Actually, there are some more things you should consider. I've investigated and put down at the next as an answer. (NSURLSessionDownloadTask move temporary file) A sample project is also available.