Search code examples
swiftswift3nsurlsessiondownloadtask

Multilple Downloads not working while using URLSessionDownloadTask in Swift 3.0


I am trying to download multilple files using the session download task and following happens:

  1. First download starts. I guess it creates a temporary file for example CFNetworkDownload_Kx54Ke.tmp.

  2. Soon after my second download start which by the way uses the same session object but a different downloadtask object.

  3. I see that my first download stop and errors out with following error :

    __NSCFLocalDownloadFile: error 2 opening for ioChannel, file: /private/var/mobile/Containers/Data/Application/E88FD72B-AB73-402E-B264-D5827BA2023C/tmp/CFNetworkDownload_Kx54Ke.tmp

  4. My second download however finishes with no issues.

My session code. I am just passing a URL to this method and session is created only once in the life cycle of the app:

//creating session only once in the app life cycle

init() {

    super.init()
    let configuration = URLSessionConfiguration.default
    self.session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    }

//calling download method from my viewcontroller
func download(url : URL ){
let request = URLRequest(url: url)
            let downloadTask : URLSessionDownloadTask

                 downloadTask  = self.session!.downloadTask(with: request)


            downloadTask.resume()
}

UPDATE: Calling each different download operation inside operation queue block works and I can see the downloads being in parallel. However I would still like to confirm if this behavior is expected with Swift 3 in urlsessiondownload task.


Solution

  • I found the issue. It was a stupid mistake on my end. I was clearing out the temp directory on every download call. First download clears temp directory and create a temp file. Second download call clears out the temp directory including the temp file of the first download.

    I had to move the clear temp directory call to a location where it's called only once.