gpt4 book ai didi

swift - AlamoFire:如何快速获取下载图像的文件大小?

转载 作者:行者123 更新时间:2023-11-28 08:33:33 25 4
gpt4 key购买 nike

我尝试过使用 Alamofire 和 alamofireimage,但似乎无法始终如一地获取下载图像的文件大小。我使用错误的方法吗?因为如果 Alamofire 下载了图像,它肯定会知道文件大小是多少?

这是我正在使用的示例代码

 Alamofire.request(.GET, imageUrlToShow)

.responseImage { af_image in
debugPrint(af_image)

print(af_image.request) // Sometimes Content-Length is returned by other times not

if af_image.result.isFailure {
print("error")
completionhandler(imageInfo: nil, error: af_image.result.description)
}
if af_image.result.isSuccess {

if let serverResponse = af_image.response {
let serverHeaders = serverResponse.allHeaderFields

if let imageSize = serverHeaders["Content-Length"] as? String {
print("we got an imagesize")
}

最佳答案

这是最后一个正确的syntax对于最新版本(AlamofireImage 2.4.0,依赖于 Alamofire 3.3):

import AlamofireImage

var ext: String! = "jpeg"

self.ext = "png"
Alamofire.request(.GET, "https://httpbin.org/image/png")
.responseImage { response in
debugPrint(response)

print(response.request)
print(response.response)
debugPrint(response.result)

if let image = response.result.value {
print("image downloaded: \(image)") // example: background.png
var imgData: NSData!
switch self.ext {
case "png":
imgData = NSData(data: UIImagePNGRepresentation(image)!)
case "jpeg":
imgData = NSData(data: UIImageJPEGRepresentation((image), 1)!)
default:
break
}
if let data = imgData {
print("Size of Image: \(data.length) bytes")
}
}
}

您也可以使用一般的Alamofire framework ,正是这个例子(下载文件或恢复已经在进行中的下载)。

Alamofire.download(.GET, "https://httpbin.org/stream/100") { temporaryURL, response in
let fileManager = NSFileManager.defaultManager()
let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let pathComponent = response.suggestedFilename

return directoryURL.URLByAppendingPathComponent(pathComponent!)
}

Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
print(totalBytesRead)

// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes read on main queue: \(totalBytesRead)")
}
}
.response { _, _, _, error in
if let error = error {
print("Failed with error: \(error)")
} else {
print("Downloaded file successfully")
}
}

关于swift - AlamoFire:如何快速获取下载图像的文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38372494/

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