gpt4 book ai didi

ios - Alamofire progress.fractionCompleted 为空

转载 作者:行者123 更新时间:2023-11-28 15:29:21 31 4
gpt4 key购买 nike

我使用 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 上找到了一个提示——设置服务器响应header("内容长度:".$size);但这没有帮助,有人知道吗?)所有其他使用此框架的人都可以正常工作

最佳答案

对于许多人来说,确保网络服务器提供正确的 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 将此大小添加到服务器端的 header 。您只需在上面的代码中使用 Content-Length-Decompressed 而不是 Content-Length

关于ios - Alamofire progress.fractionCompleted 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44885534/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com