我使用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上发现了一个提示-设置服务器响应头(“Content-length:".$size);但它没有帮助,有人知道吗?)这个框架的所有其他功能都是正常工作的。
发布于 2017-10-11 19:19:10
对于许多人来说,确保see服务器提供正确的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 )
}
}
}
}
}
}
}如果您使用Alamofire responseJSON并有一个压缩文件,如.json.gz,则必须知道未压缩文件的大小才能计算进度,因为progress.completedUnitCount会给出未压缩文件的完整字节数。
您可以使用Content-Length-Decompressed将此大小添加到服务器端的标头。在上面的代码中,您只需使用Content-Length-Decompressed而不是Content-Length。
https://stackoverflow.com/questions/44885534
复制相似问题