3 networking download ios swift alamofire
我目前正在开发一个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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
大多数代码仅用于上下文.
我发现,直到Alamofire 3才有这样的电话:
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total Bytes Expected: \(totalBytesExpectedToRead)")
}
Run Code Online (Sandbox Code Playgroud)
这不再存在了,我想知道如何才能获得相同的功能.
先感谢您!
在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)")
}
Run Code Online (Sandbox Code Playgroud)
可以实现
// Alamofire 4
Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default)
.downloadProgress { progress in
print("Progress: \(progress.fractionCompleted)")
}
Run Code Online (Sandbox Code Playgroud)
返回的progress对象属于ProgressApple的Foundation框架类型,因此您可以访问该fractionCompleted属性.
有关更改的详细说明,请参阅Alamofire 4.0迁移指南的" 请求子类"部分.Alamofire GitHub仓库中的拉取请求1455引入了新的Progress API,也可能有所帮助.