zevonja
zevonja

Reputation: 193

AFNetworking image download without using AFImageRequestOperation

I want to download a image from url and get NSData in response object.

This is how I set up the operation:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"image/jpeg"];
manager.responseSerializer = responseSerializer;

AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer setValue:@"image/jpeg" forHTTPHeaderField:@"Accept"];
[requestSerializer setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = requestSerializer;

[manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSData *data = responseObject;

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

Response object is always nil, url is correct, when openned in browser it shows up the image, the operation descriptions shows content-length and content type(image/jpeg), but response object doesn't seem to pick it up.

Thank you

Answer: instead of responseObject, operation.reponseData need to be used.

Upvotes: 0

Views: 1461

Answers (1)

vikingosegundo
vikingosegundo

Reputation: 52237

You will need to tell AFNetworking that you expect image data and that to should be deserialized as that.

manager.responseSerializer = [AFImageResponseSerializer serializer];

AFImageResponseSerializer Class Reference

By default, AFImageSerializer accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage:

image/tiff
image/jpeg
image/gif
image/png
image/ico
image/x-icon
image/bmp
image/x-bmp
image/x-xbitmap
image/x-win-bitmap

Answer: instead of responseObject, operation.reponseData need to be used.

if you would user proper serialization, it would be responseObject, transformed into a object you can immediately use. operation.reponseData contains the raw data sent from the server. usually it is not what you need.

Upvotes: 3

Related Questions