ios - 快速查找文件的下载进度

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

提前致谢

最佳答案

进度状态可以计算在

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

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

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

查看:http://goo.gl/veRkA7

关于ios - 快速查找文件的下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923332/

相关文章:

ios - 在某些 Controller 中禁用横向时,横向启动应用程序会扭曲整个应用程序

ios - 更改 UIAlertcontroller 背景颜色

download - TYPO3 extbase FAL 文件下载

ios - NavigationItem titleView 出现在左侧一段时间,然后移至中心

ios - 无法将类型 '[ViewController.MyStruct]' 的值分配给类型 '[ViewController.MyOtherStruct]'

ios - Youtube 风格的投票。这是什么逻辑?

swift - 使用带有惰性属性的函数调用会导致编译错误

ios - Alamofire 5.0+ MultipartFormData 上传不记名 token

jsf - 如何从 JSF 支持 bean 提供文件下载?

python - 如何使用 Python 在 chrome 中将文件下载到所需位置?