问题描述
我目前正在开发一个iOS项目,需要我一次下载10个不同的文件。我知道文件大小和所有文件的大小相结合,但我很难找到一种方法来计算所有下载任务的进度。
I'm currently working on an iOS project which requires me to download 10 different files at once. I know the file size and the size of all the files combined but I'm struggling to find a way to calculate the progress across all download tasks.
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)
}
}
}
大多数此代码仅用于上下文。
Most of this code is just for context.
我发现,直到Alamofire 3才有这个电话:
I discovered, that up to Alamofire 3 there was this call:
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)")
}
现在不再存在了,我想知道如何获得相同的功能。
This is not present anymore and I'm wondering how I can get the same functionality.
提前谢谢!
推荐答案
在Alamofire 4中,Progress API已更改。所有更改都在。
In Alamofire 4 the Progress APIs changed. All changes are explained in the Alamofire 4.0 Migration Guide.
总结最重要的更改会影响您的使用案例:
To sum up the most important changes, that affect your use case:
// 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)")
}
返回的进度
对象属于类型的Apple的Foundation框架,因此您可以访问 property。
The returned progress
object is of the Progress
type of Apple's Foundation framework, so you can access the fractionCompleted
property.
有关更改的详细说明,请参阅。
Alamofire GitHub仓库中的拉取请求介绍了新的Progress API也可能有所帮助。
Detailed explanation of the changes can be found in the Request Subclasses section in the Alamofire 4.0 Migration guide.The pull request 1455 in the Alamofire GitHub repo introduces the new Progress APIs and might be of help as well.
这篇关于如何使用Alamofire 4以字节为单位获得下载进度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!