我搜索过,但只在 Objective C 中没有找到相关答案。有没有办法在 Swift 中找到文件下载的进度,以便向用户显示?我是 iOS 编程的新手,我尝试使用 NSURLSession 但没有成功。
编辑: 我已使用此方法,如 this 中所示发布,但我似乎无法理解如何获取进度状态:
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()
}
提前致谢
最佳答案
进度状态可以计算在
URLSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)
这是协议(protocol) NSURLSessionDownloadDelegate 的三个必需方法之一。在我的例子中,方法的代码如下所示:
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
}
}
我创建了一个小项目,它实现了三种不同的方法:
- 同步下载
- 异步下载
- 下载进度
关于ios - 快速查找文件的下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923332/