How to check resume capability of current URLSessionDownloadTask?

Viewed 353

Currently i'm working on downloading a file from server, and this is working good.


my question is how would i know that url has resume capability or not before actual download started?
bellow is some code snippet,

class Downloader:NSObject,URLSessionDownloadDelegate {
    /*
     SOME PROPERTIES & DECLARATIONS
     */

    override init() {
        super.init()
        let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: url.absoluteString)
        backgroundSessionConfiguration.networkServiceType = .default
        self.defaultSession = URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
    }

    func start(_ block:DownloaderCompletionHandler?) {
        guard self.input == nil else { return }
        guard self.output == nil else { return }
        if let data = self.resumableData {
            self.downloadTask = self.defaultSession.downloadTask(withResumeData: data)
        }else {
            let request = URLRequest(url: self.input!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 0.60)
            self.downloadTask = self.defaultSession.downloadTask(with: request)
        }
        self.downloadTask.resume()
    }
    func pause() {
        self.downloadTask.cancel { (data) in
            self.resumableData = data
        }
    }
}

please , guid me on this situation. THANKS IN ADVANCE

2 Answers

A download can be resumed only if the following conditions are met:

  • The resource has not changed since you first requested it

  • The task is an HTTP or HTTPS GET request

  • The server provides either the ETag or Last-Modified header (or both) in its response

  • The server supports byte-range requests

  • The temporary file hasn’t been deleted by the system in response to disk space pressure

→ Source: https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel

if you send a request with Range in HttpHeaders and receive a 206 status code in response , then you can resume the download. otherwise download can not be resumed.

read more about it here

Related