Search code examples
iosobjective-cafnetworking-2

AFNetworking 2 setImageWithURL custom response type image/jpeg


Im using AFNetworking 2. I have a UITableview and each row contains an image.

The issue is that the response type is image/pjpeg which is not an accepted type by default. To get around this I have modified AFURLResponseSerialization.m around line 599. Adding this content type to the end of the self.acceptableContentTypes declaration.

I would prefer not to modify the source. Is there a proper way to do this in 2.x?

NSString *url = [NSString stringWithFormat:@"%@my/images/%@",BaseUrl,[o objectForKey:@"ID"]];
[cell.imageView setImageWithURL:[NSURL URLWithString:url]
               placeholderImage:[UIImage imageNamed:@"placeholder"]
 ];

This no longer seems to work:

[AFImageRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"image/jpeg"]]

Update:

I can see the error using the following code:

   NSURLRequest *urlRequest = [NSURLRequest requestWithURL: [NSURL URLWithString: url]];

__weak UITableViewCell *weakCell = cell;
[cell.imageView setImageWithURLRequest:urlRequest
                      placeholderImage:[UIImage imageNamed:@"placeholder"]
                        success: ^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                            __strong UITableViewCell *strongCell = weakCell;

                            strongCell.imageView.image = image;

                            [tableView reloadRowsAtIndexPaths: @[indexPath]
                                             withRowAnimation: UITableViewRowAnimationNone];
                            NSLog(@"Your image request succeeded!");
                        } failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                            NSLog(@"Your image request failed...");

                            NSLog(@"Error: %@", error);
                            NSLog(@"Error: %@", response);
                        }

 ];

Here is the error:

Error: Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: image/pjpeg"

Solution

  • You can set your own imageResponseSerializer on a UIImageView instance:

    AFImageResponseSerializer *serializer = [[AFImageResponseSerializer alloc] init];
    serializer.acceptableContentTypes = [serializer.acceptableContentTypes setByAddingObject:@"image/pjpeg"];
    cell.imageView.imageResponseSerializer = serializer;
    
    NSString *url = [NSString stringWithFormat:@"%@my/images/%@",BaseUrl,[o objectForKey:@"ID"]];
    [cell.imageView setImageWithURL:[NSURL URLWithString:url]
                   placeholderImage:[UIImage imageNamed:@"placeholder"]
    ];