Download a file and track progress with NSURLSessionDownloadTask

fabiodelorenzo
Posts: 65
Joined: Thu Oct 03, 2013 5:54 pm

Download a file and track progress with NSURLSessionDownloadTask

Postby fabiodelorenzo » Tue Jan 05, 2016 6:33 pm

The UIController extends NSURLSessionDownloadDelegate

Code: Select all

class ViewController: UIViewController, NSURLSessionDownloadDelegate {

    private let MY_URL = "http://ipv4.download.thinkbroadband.com/200MB.zip"
    private var downloadTask: NSURLSessionDownloadTask?


define a button to run our task

Code: Select all

    @IBAction func DownloadAction(sender: AnyObject) {
        createDownloadTask()
    }


The real task

Code: Select all

    func createDownloadTask() {
        let downloadRequest = NSMutableURLRequest(URL: NSURL(string: MY_URL)!)
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
       
        downloadTask = session.downloadTaskWithRequest(downloadRequest)
        downloadTask!.resume()
    }


define the delegates

Code: Select all

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        PercText.text = String(progress) + " [Total=" + String(totalBytesWritten) + "|" +
            String(totalBytesExpectedToWrite) + "]"
    }


to be called when the trasnsfer is complete

Code: Select all

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        PercText.text = "Download finished"
    }


Code: Select all

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        if let _ = error {
            PercText.text = "Download failed"
        } else {
            PercText.text = "Download finished"
        }
    }


}

Return to “NSURLSession for networking and JSON”

Who is online

Users browsing this forum: No registered users and 1 guest