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

Find the Download Progress of a file in swift

我搜索过,但仅在 Objective C 中没有找到相关答案。有没有办法找到 Swift 中文件的下载进度,以便向用户显示?我是 iOS 编程的新手,我尝试使用 NSURLSession 但没有成功。

编辑: 我已经使用了 this post 中看到的这种方法,但我似乎无法理解如何获取进度状态:

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()
}

提前致谢

假设你正在下载一个文件,有一个 NSURLSessionTask 的子类,叫做 NSURLSessionDownloadTask。以下是关于特定功能的 NSURLSession 文档的摘录:

Periodically informs the delegate about the download’s progress.

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

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

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

进度状态可以计算在

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

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

上有个fractionCompleted属性

游乐场示例:

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()