如何在下载失败时使AFNetworking设置默认图像?

时间:2016-09-20 16:25:37

标签: ios objective-c afnetworking-3

我想做以下事情:

  1. 当图片加载时=>必须显示指示加载的微调器或其他图像;
  2. 加载图片时=>必须显示图像;
  3. 当图像失败时=>必须显示静态“无图像可用”图像。
  4. 我试过了:

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

    但我无法弄清楚如何处理失败事件。

1 个答案:

答案 0 :(得分:1)

为什么不使用

setImageWithURLRequest:placeholderImage:success:failure:

From the doc

并在故障块中设置想要的占位符图像?

示例:

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