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
When you go into the Play Store and download an app, you'll see a grayed-out icon appear on your home screen. This icon will be surrounded by a progress bar that continues to fill up as the download is completed.
The URLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn't running or, in iOS, while your app is suspended.
You can achieve this using percent_indicator package. On this link, it is already implemented to show download progress using percent_indicator. Though it is for individual list item but you can implement it similar way for button.
You can see the progress of a download in the Purchases section of the App Store.
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:
Check it out: http://goo.gl/veRkA7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With