UKDataGeek
UKDataGeek

Reputation: 6882

AlamoFire: how to get file size of downloaded image in swift?

I have tried using Alamofire, and alamofireimage but can't seem to get the file size of a downloaded image consistently. Am I using the wrong approach? because surely if Alamofire has downloaded the image, it will know what the filesize is?

Here is the example code I am using

 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")
}

Upvotes: 2

Views: 3293

Answers (2)

Alessandro Ornano
Alessandro Ornano

Reputation: 35372

This is the last correct syntax for the latest version (AlamofireImage 2.4.0 with dependencies from 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")
                 }
             }
         }

You can also use the general Alamofire framework , exactly this example (download files or resume a download that was already in progress).

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")
             }
         }

Upvotes: 1

Jon Shier
Jon Shier

Reputation: 12770

You can use .responseData() to get the data that was returned, and get the size from that. Unfortunately the accuracy of Content-Length depends on the server returning the correct information. As you've seen that's not always an accurate indicator and not always included in responses.

Upvotes: 0

Related Questions