2

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.

namaama
  • 57
  • 4

1 Answers1

1

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.

beshio
  • 794
  • 2
  • 7
  • 17
  • 1
    I read your answer , but when you say kind of expected what do you mean? Shoulnt i expect didCompletedWithError to be actived on app relunch? But it doesnt unless i hit start again thats quite un-expected why should a response from previos task only ny creating a new one? I just want a way to get my resumeData from previos task inside error on this function just to resume download and thats it and i want it on app relunch – namaama Aug 31 '18 at 03:48
  • I meant that "your scenario can happen, and you have to be ready against it". Sorry for the confusion. The point is that we may receive didCompleteWithError and didFinishDownloadingTo twice for the same thing after we create new session w/ the same config at the next launch. Some other unwanted scenarios/behaviors (of iOS) are described in my other [answer](https://stackoverflow.com/questions/45338412/nsurlsessiondownloadtask-move-temporary-file/45904207#45904207). – beshio Aug 31 '18 at 08:17