Does AFNetworking cache images load automatically or do we have to do it manually?

折月煮酒 提交于 2019-12-05 16:34:29

tl;dr

Use -setImageWithURLRequest:placeholderImage:success:failure:

  NSURLRequest *imageRequest =
      [NSURLRequest requestWithURL:[NSURL URLWithString:imgurl]
                       cachePolicy:NSURLRequestReturnCacheDataElseLoad
                   timeoutInterval:60];

  [cell.detailImageView setImageWithURLRequest:imageRequest
                              placeholderImage:nil
                                       success:nil
                                       failure:nil];

Image Cache + AFNetworking

Import the UIImageView+AFNetworking header and viola! UIImageView class now has several methods to download images and also, to cache them!

In-memory Caching: You can use following methods for simple in-memory caching.

Image will be retrieved from the in-memory cache, if the image exists, otherwise it will be downloaded from the URL and stored in the in-memory cache.

Example:

[imageView setImageWithURL:[NSURL URLWithString:imageURL]];

//here, placeholder image is set immediately.
[imageView setImageWithURL:[NSURL URLWithString:imageURL]
          placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Disk Caching: You can use following method if you need to cache the image for longer than the user’s session. (tip: check NSURLRequestCachePolicy in NSURLRequest class)

Note: If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with self.image = image is applied.

Example:

  NSURLRequest *imageRequest =
      [NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]
                       cachePolicy:NSURLRequestReturnCacheDataElseLoad
                   timeoutInterval:60];

  [imageView setImageWithURLRequest:imageRequest
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                            success:nil
                            failure:nil];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!