How to download image with AFNetworking 2.0?

IphoneIosXcodeAfnetworking 2

Iphone Problem Overview


Appareantly there is no AFImageRequestOperation, but only AFImageResponseSerializer and frankly I don't get it or maybe I'm just looking too long through AFNetworking site... Downloading images with previous AFNetworking was like a charm. I'd hate to go back to older AFnetworking, since I did almost all stuff via the new version... Anyone?

Iphone Solutions


Solution 1 - Iphone

SO you want something like this for 2.0.

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response: %@", responseObject);
    _imageView.image = responseObject;

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Image error: %@", error);
}];
[requestOperation start];

As mentioned by Adam you can also do something like the below if you are just wanting to throw it into an imageView

[myImageView setImageWithURL:[NSURL URLWithString:@"http://sitewithimage.com/images/myimage.png"]];

Solution 2 - Iphone

for old version, there is no responseSerializer, you can also

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
//requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response: %@", responseObject);
    _imageView.image = [UIImage imageWithData:responseObject];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Image error: %@", error);
}];
[requestOperation start];

Solution 3 - Iphone

For people using AFNetworking in Swift, above solution can be written as below

    let requestOperation : AFHTTPRequestOperation = AFHTTPRequestOperation(request: urlRequest)
    requestOperation.responseSerializer = AFImageResponseSerializer()

    requestOperation.setCompletionBlockWithSuccess({ (requestOperation, responseObject) in
       print(responseObject)
        _imageView.image = responseObject as? UIImage
        
    }) { (requestOperation, error) in
       print(error)
    }
    requestOperation.start()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionraistlinView Question on Stackoverflow
Solution 1 - IphoneBotView Answer on Stackoverflow
Solution 2 - IphonelbsweekView Answer on Stackoverflow
Solution 3 - IphonePenkey SureshView Answer on Stackoverflow