Search code examples
iosobjective-cafnetworking-3

How to make AFNetworking set a default image when the download fails?


I want to do the following:

  1. When the image is loading => Must display a spinner or another image indicating loading;
  2. When the image is loaded => Must display the image;
  3. When the image fails => Must display a static "no image available" image.

I tried:

- (void)setImageWithURL:(NSURL *)url
   placeholderImage:(UIImage *)placeholderImage

But I couldn't figure out how to handle the failure event.


Solution

  • Why don't you use

    setImageWithURLRequest:placeholderImage:success:failure:
    

    From the doc

    And set the wanted placeholder image in the fail block?

    Example:

    NSURLRequest * aURLRequest = [[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString: @"A-URL"]];
    UIImageView * img = [[UIImageView alloc] init];
    __weak UIImageView* weakImg = img;
    [img setImageWithURLRequest:aURLRequest
               placeholderImage:nil
                        success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                            //default
                        }
                        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                            weakImg.image = [UIImage imageNamed:@"fallbackImage"];
                        }];