如何使用Alamofire 4以字节为单位获得下载进度?

我目前正在开发一个iOS项目,需要我一次下载10个不同的文件。 我知道文件大小和所有文件的大小相结合,但我很难找到一种方法来计算所有下载任务的进度。

progress.totalUnitCount = object.size // The size of all the files combined for file in files { let destination: DownloadRequest.DownloadFileDestination = { _, _ in let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) let documentDirectoryPath: String = path[0] let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath) return (destinationURLForFile, [.removePreviousFile, .createIntermediateDirectories]) } Alamofire.download(file.urlOnServer, to: destination) .downloadProgress(queue: .main, closure: { progress in }) .response { response in if let error = response.error { print(error) } } } 

这些代码大部分仅用于上下文。

我发现,直到Alamofire 3才有这样的电话:

  .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)") } 

这不再存在,我想知道如何才能获得相同的function。

先谢谢你!

在Alamofire 4中,Progress API发生了变化。 所有更改都在Alamofire 4.0迁移指南中进行了解释。

总结影响您的用例的最重要的更改:

 // Alamofire 3 Alamofire.request(.GET, urlString, parameters: parameters, encoding: .JSON) .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)") } 

可以实现

 // Alamofire 4 Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default) .downloadProgress { progress in print("Progress: \(progress.fractionCompleted)") } 

返回的progress对象属于Apple的Foundation框架的Progress类型,因此您可以访问fractionCompleted属性。

有关更改的详细说明, 请参阅Alamofire 4.0迁移指南的“ 请求子类”部分 。 Alamofire GitHub仓库中的拉取请求1455引入了新的Progress API,也可能有所帮助。