One of the most common tasks that iOS -and not only- developers are called to perform in their programming endeavours is fetching and managing remote images that should be displayed to an app. For instance, suppose that you’re building the next great messaging application where obviously users have contacts. Those contacts have avatar images residing to a server. When users connect to the app then avatars must be downloaded in order to be used by the app. Or, another example, think of an app that manages the event of a worldwide convention, and among its features is the list of all attendees. Their images must be fetched and handled by the app, and displayed properly when necessary.
What makes things complicated is the fact that image fetching is an asynchronous process. When fetching multiple images then it’s really easy to display the wrong image to the wrong place in certain cases. Think of the contact list again, which is a list of images with text at its simplest form. Displaying fetched avatar images to the proper contacts can end up being a hell depending on how image handling has been implemented. It would be really bad to see the app displaying the wrong avatar next to each name, and it would be even worse to have avatar images being replaced by other avatar images when contacts appear and disappear while scrolling. Have you seen this maybe? A perfect chaos and no consistency at all!
Another troubling point can be the way images are handled locally once they are fetched. Are there any rules about naming or storing details? Are there best and worst practices one should follow? Should images be stored in documents or in caches directory? These and more questions will most probably arise when building an app and it’s about time to deal with remote images. The answers though should not be given and implemented when an actual application is being built; that kind of issues should be already fixed and be part of the solution, not the problem.
So, here we come. In this tutorial I will present you a simple, yet quite effective recipe that makes fetching remote images and then handling them locally a really straightforward task. I’ll show you how to create a handy tool that you’ll be able to use right when it’s needed, and you won’t need to worry anymore about all that I described above. Even if you won’t use what we’ll build here eventually, you might get some ideas to apply in your own solutions. So, keep on reading to find out some really interesting stuff.