在swift中找到文件的下载进度

时间:2015-01-13 13:30:25

标签: ios swift download progress nsurlsession

我已经搜索但是没有在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()
}

提前谢谢

3 个答案:

答案 0 :(得分:12)

可以在

中计算进度状态
URLSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)

这是协议 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
    }
}

我创建了一个小项目,它实现了三种不同的方法:

  • 同步下载
  • 异步下载
  • 下载进度

检查出来:http://goo.gl/veRkA7

答案 1 :(得分:4)

假设您正在下载文件,那么只有NSURLSessionTask的子类就是NSURLSessionDownloadTask。以下是关于特定功能的NSURLSession文档的摘录:

  

定期向代表通知下载进度。

func URLSession(_ session: NSURLSession,
    downloadTask downloadTask: NSURLSessionDownloadTask,
    didWriteData bytesWritten: Int64,
    totalBytesWritten totalBytesWritten: Int64,
    totalBytesExpectedToWrite totalBytesExpectedToWrite: Int64
)

例如,您可以通过执行以下操作将进度输出到控制台:

println("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")

答案 2 :(得分:1)

您可以简单地观察progress对象的URLSessionDataTask属性。而且您无需像其他答案在这里建议的那样计算进度。 fractionCompleted上有一个Progress属性。

游乐场示例:

import Foundation
import PlaygroundSupport

let page = PlaygroundPage.current
page.needsIndefiniteExecution = true

let url = URL(string: "https://source.unsplash.com/random/4000x4000")!
let task = URLSession.shared.dataTask(with: url) { _, _, _ in
  page.finishExecution()
}

// Don't forget to invalidate the observation when you don't need it anymore.
let observation = task.progress.observe(\.fractionCompleted) { progress, _ in
  print(progress.fractionCompleted)
}

task.resume()