How to download image with AFNetworking 2.0? How to download image with AFNetworking 2.0? ios ios

How to download image with AFNetworking 2.0?


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"]];


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];


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()