我使用Alamofire框架从服务器下载图像。我需要进度下载,但我无法得到它。
Alamofire.download(requestForImage, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil, to: self.destination)
.downloadProgress{ progress in
self.progressView.progress = progress.fractionCompleted
print(progress.fractionCompleted)
}
.response{ response in
if let headers = response.response?.allHeaderFields as? [String: String]{
print("headers = \(headers)")
// ...
}
if response.error == nil, let imagePath = response.destinationURL?.path {
self.progressView.progress = 1
let image = UIImage(contentsOfFile: imagePath)
print("Image is successfully downloaded!")
self.addNewImageToTheScrollView(img: image)
}
}
}
progress.fractionCompleted = 0.0,progress.totalUnitCount = -1 我在alamofire github上找到了一个提示 - 设置服务器响应 标题("内容长度:"。$ size); 但它没有任何帮助,有任何人有任何想法?)所有其他与此框架一样的工作
答案 0 :(得分:1)
对于很多人来说,它可以确保网络服务器提供正确的Content-Length
,请参阅https://github.com/Alamofire/Alamofire/issues/1467
如果这没有帮助,你可以先做一点工作,先读头,阅读Content-Length
,然后自己计算进度。
Alamofire.request( url, method: .head )
.validate()
.response { response in
if let error = response.error {
print( "ERROR: Can't get head for \(url) \(error)" )
} else {
if let response = response.response {
if let contentLengthHeader = response.allHeaderFields["Content-Length"],
let contentLengthInt = Int( "\(contentLengthHeader)" )
{
Alamofire.download( url,
method: .get, parameters: nil,
encoding: URLEncoding.default, headers: nil, to: destination
)
.downloadProgress{ progress in
print( progress.fractionCompleted )
print( Float( progress.completedUnitCount ) / Float( contentLengthInt ) )
}
.validate()
.response{ response in
if let error = response.error {
print( "ERROR: Can't get image for \(url) \(error)" )
} else {
if let imagePath = response.destinationURL?.path {
let image = UIImage( contentsOfFile: imagePath )
}
}
}
}
}
}
}
如果您使用Alamofires responseJSON
并拥有压缩文件,例如.json.gz
,您必须知道未压缩文件的大小才能计算进度,因为progress.completedUnitCount
会为您提供已完成的字节未压缩文件的。
您可以使用Content-Length-Decompressed
将此大小添加到服务器端的标头中。您只需在上面的代码中使用Content-Length-Decompressed
代替Content-Length
。