Get image data with Alamofire request
Asked Answered
C

4

13

I've updated my code to Swift 3 and am having trouble with the migration to Alamofire 4.0. I've used the Alamofire migration guide to successfully make most of the necessary modifications, but am still having trouble getting image data.

The old Swift 2 / Alamofire 3 code (worked as intended):

func beginGetImageRequest() {
    if let imagePath = thumbPath {
        request = Alamofire.request(.GET, imagePath).response(completionHandler: { (_, _, imageData, error) -> Void in
            if error != nil {
                NSLog("Error downloading thumbnail image: \(error)")
            } else {
                if let downloadedImage = UIImage(data: imageData!) {
                    self.imageView.image = downloadedImage
                }
            }
        })
    }
}

My attempt at updating to Alamofire 4:

func beginGetImageRequest() {
    if let imagePath = thumbPath {
        request = Alamofire.request(imagePath, method: .get, parameters: [:], encoding: JSONEncoding.default)
            .validate { request, response, imageData in
                if let downloadedImage = UIImage(data: imageData!) {
                    self.imageView.image = downloadedImage
                } else {
                    print(response)
                    print(imageData)
                }
                return .success
            }
    }
}

print(imageData) outputs Optional(306 bytes). The image should be about 40 kb, which tells me the problem is with how I am implementing request, not with how I am converting the data to a UIImage.

Here is the output for print(response)

<NSHTTPURLResponse: 0x618000221660> { URL: http://209.126.98.238/cache/igames_thumb/images/games/53848027743af.jpeg } { status code: 400, headers {
    Connection = close;
    "Content-Encoding" = gzip;
    "Content-Length" = 245;
    2016-10-04 21:54:53.653480 EyeGames[74216:3416747] [] nw_connection_send_stats_report 21 Generated report: 
    Delegated:                                  0
    Report reason:                              app data stall
    TCP statistics report:                      
    Time to DNS start:                       0 ms
    Time to DNS resolved:                    0 ms
    DNS resolved time:                       0 ms
    DNS answers cached:                      0
    Interface type:                          1
    Time to TCP start:                       3 ms
    Time to TCP establishment:               223 ms
    Connection establishment:                220 ms
    Flow duration:                           11447 ms
    Connected interface type:                1
    Connected:                               1
    Traffic class:                           0
    Cellular fallback:                       0
    Cellular RRC connected:                  0
    Kernel reported stalls:                  0
    Kernel reported connection stalls:       0
    Kernel reported read stalls:             0
    Kernel reported write stalls:
"Content-Type" = "text/html; charset=iso-8859-1";
    Date = "Tue, 04 Oct 2016 18:54:43 GMT";
    Server = "Apache/2.2.22 (Debian)";
    Vary = "Accept-Encoding";
} }
Cicatrix answered 4/10, 2016 at 17:51 Comment(3)
And what the response contains? you should start thereKaraganda
@Karaganda Edited my question to include the output from the responseCicatrix
Your are getting 400 error code. Your request is malformed. Try changing the encode to URLKaraganda
I
28

The folks over at Alamofire made an image component library, AlamofireImage. It handles all this stuff for you to make your life easier. Add it to your project and then you can just do this:

import Alamofire
import AlamofireImage

Alamofire.request(imageUrl, method: .get).responseImage { response in
    guard let image = response.result.value else {
        // Handle error
        return
    }
    // Do stuff with your image
}
Incorporable answered 4/10, 2016 at 23:2 Comment(2)
This is perfect! Didn't know about this component library. Thank you!Cicatrix
Do I need to add Alamofire and AlamofireImage in my project to use AlamofireImage or just adding AlamofireImage alone would work, to run the above code.Tentacle
E
3

If you really want to use Alamofire for downloading an image, you should try URLEncoding instead of JSONEncoding, just as Godfather suggested in the comments above. Although I would recommend using Kingfisher instead. It will take you a single line of code instead of a GET request method with Alamofire:

self.imageView.kf.setImage(with: URL(string: imagePath))
Espresso answered 4/10, 2016 at 22:5 Comment(1)
Since my project is already very dependent on Alamofire for both image and non-image issues, I prefer to stick with Alamofire. But I will keep Kingfisher in mind for future projects. Thank you for your input!Cicatrix
T
0

You can have image cache problem where you get previous saved image.

To prevent this, you can remove cache for the url before calling Alamofire.request

let urlRequest = URLRequest(url: URL(string: url)!)
URLCache.shared.removeCachedResponse(for: urlRequest)
Trunnion answered 18/12, 2017 at 13:21 Comment(0)
D
0

You can directly download image from given Url.

import AlamofireImage

let URL = URL(string: "your image url")

imageView.af_setImage(withURL: URL!)

Hope this will work :)

Drusilladrusus answered 13/12, 2018 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.