Find the Download Progress of a file in swift

loopidio picture loopidio · Jan 13, 2015 · Viewed 14.7k times · Source

I have searched but haven't found a relevant answer only in Objective C. Is there a way to find the progress of the download of a file in Swift, so that to show it to user? I am new to iOS programming and I have tried with NSURLSession but without success.

EDIT: I have used this method as seen in this post, but I can't seem to understand how to get the progress status:

func downloadFile(page: NSString){
    finished = false
    var statusCode:Int = 0
    println("Download starting")
    let url = NSURL(string: page)

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in

        if error != nil {
            println("download failed with error \(error?.localizedDescription)")
        } else {
            println("Expected Content-Length \(response.expectedContentLength)")
            self.contentLength = response.expectedContentLength
            if let httpResponse = response as? NSHTTPURLResponse {
                println("Status Code of number \(self.countDownload) is \(httpResponse.statusCode)")
                statusCode = httpResponse.statusCode
            }
        }
    }
    task.resume()
}

Thank you in advance

Answer

evpozdniakov picture evpozdniakov · Mar 31, 2015

The progress status can be calculated in

URLSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)

This is a one of three required methods of protocol NSURLSessionDownloadDelegate. In my case the code of the method looks like this:

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    // println("download task did write data")

    let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)

    dispatch_async(dispatch_get_main_queue()) {
        self.progressDownloadIndicator.progress = progress
    }
}

I've created a small project, which implements three different approaches:

  • download synchronously
  • download asynchronously
  • download with progress

Check it out: http://goo.gl/veRkA7