AFNetworking is one of the most popular open-source networking frameworks for iOS. You’re probably already using it, but if you’re not, you should consider it. One of the lesser-known features of AFNetworking is the ability to easily load an image from a URL to be used in a
Simple Image Caching
Start by importing the
UIImageView+AFNetworking header and several useful methods will be added to the
For simple in-memory caching, you can use the
setImageWithURL:placeholderImage: methods and the image will be retrieved from the in-memory cache, if the image exists, otherwise it will be fetched from the URL and stored in the cache.
1 2 3 4 5
If you need to cache the image for longer than the user’s session, you can use the
setImageWithURLRequest:placeholderImage:success:failure: method. Set the caching policy on your
NSURLRequest to whatever you need and you’re good to go!
1 2 3 4 5 6 7 8
Note that if you supply a success block, you will be responsible for setting the image within the success block. If one is not provided, AFNetworking will set the image for you.
If AFNetworking isn’t your thing, I highly recommend using the excellent SDWebImage instead.