iosswiftnsurlsessiondownloadtasknsurlsessiondatatask

Should I choose URLSessionDataTask or URLSessionDownloadTask for getting image


I use URLSession and URLSessionDataTask to get an image from server and display it in an app. I had a look here. It looks like URLSessionDownloadTask has more options.

Currently I use the following code for getting the image:

let task = URLSession.shared.dataTask(with: url) {(data, response, error) in

    guard error == nil else {
        completion(error, nil)
        return
    }

    completion(nil, data)            
}        
task.resume()

I'd like to be able to suspend, cancel and resume the process of getting the image from the server. I see in the documentation that URLSessionDataTask also has these options. But it's also written for the suspend method of URLSessionTask that:

A download task can continue transferring data at a later time. All other tasks must start over when resumed.

So my question is: Should I change the implementation to use URLSessionDownloadTask for getting the images if I need to be able to stop getting the image at some point and resume later without losing the current progress? Thank you in advance.


Solution

  • NSURLSessionDataTask : Data tasks exchange data using NSData. NSURLSessionDataTask is not supported in Background Sessions because it does not write the content in a form of a local file(stored in memory). Therefore it can not be resumed later onwards .

    NSURLSessionDownloadTask : NSURLSessionDownloadTask directly writes the response data to a temporary file. It supports background downloads when the app is not running and in your case does allow resume of downloads.

    The question is why do you want to resume the download of an "image" you are trying to display in the App . Will it ever change ? or will it always be the same through out the App. If it has a chance of changing in the future i think you should stick to URLSessionDataTask because imo it will eat up local storage to download and write images over and over again.

    The risk of using NSURLSessionDownloadTask is that prior to download you will have to check if the download space available on the device is sufficient to go ahead with , in other words it is a must to handle fileSize errors as apple thinks its upto the developer to meet those requirements