[英]How to get the download progress in bytes using 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)")
}
这不再存在,我想知道如何获得相同的功能。
先感谢您!
在 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,可能也有帮助。
阿拉莫火 5,斯威夫特 5
AF.download(urlString)
.downloadProgress { progress in
print("Download Progress: \(progress.fractionCompleted)")
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.