Image caching in Xamarin Forms

From https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/images?tabs=macos
Share on facebook
Share on twitter
Share on linkedin

Someone asked me about an issue they were having when showing a ListView that had an image for each cell. When the user would scroll the images would flicker and the UI would turn a bit slow. The images were being loaded from the internet.

The problem the person was having was that they were not using a correct caching strategy for the images and now I’m going to explain how you can fix this problem in case it happens to you.

Enough context, let’s do the caching

If you want to add cache to your image you should use something like this:

Some explanations ensue

When you want to show an image you know you specify the Source of the Image. Probably as a URL or a route to a resource, both look like strings but if you look a bit further you will notice the Source property of the Image is actually of type ImageSource and it can be assigned any value that inherits from it.

In the code sample, we set the Source to an instance of UriImageSource. This class has more properties but the three properties we want to focus on are:

  • Uri: This is the address of the image we want to show.
  • CachingEnabled: This is a boolean value that will Enable or Disable the caching. The default value is true.
  • CacheValidity: The timestamp when the cache will be dismissed. The timestamp parameters are Days, Hours, Minutes, Seconds. In the Code sample, we are setting the cache to 7 days. In the XAML sample to 30 days.

And that’s it. Pretty concise and quite useful. Hope you liked reading it as much as I did writing this article. You can get more information on working with images and the source for the feature image in this article from the official Xamarin Documentation. Bye!

Did you like the post and Wanna leave a reply? You can mention me on twitter @eatskolnikov so we can have a conversation about it

Share it with your friends

Share on facebook
Share on twitter
Share on linkedin

Want to get these post in your inbox?

Type your email down here and you will get a weekly digest of the post here

Other articles on the site

ios

Layout safe areas for iOS in Xamarin Forms

Since the launch of the iPhone X there is a notch at the top of the screen on iOS devices that tend to be annoying to work around. You would have to add some sort of margin to avoid your controls to be overlapped by it. The problem with this

Read More »
From https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/images?tabs=macos
caching

Image caching in Xamarin Forms

Someone asked me about an issue they were having when showing a ListView that had an image for each cell. When the user would scroll the images would flicker and the UI would turn a bit slow. The images were being loaded from the internet. The problem the person was

Read More »