Xamarin.Forms caching images

loan.burger picture loan.burger · Apr 21, 2015 · Viewed 7.1k times · Source

I am using Xamarin.forms to build an application which runs on IOS, Windows Phone and Android. I need to be able cache images on the device when there is no network available.

The basics:

I'm using an MVVM approach and have a MenuViewModel with a IconImageId property which has a GUID for different images.

The Icons in my view cell then binds to this property:

var icon = new Image
{
    Aspect = Aspect.AspectFit,
    HeightRequest = 80, 
    WidthRequest = 80       
};
icon.SetBinding(Image.SourceProperty, new Binding("IconImageId",BindingMode.Default, new ImageIdToUriImageSourceValueConverter(80, 80, iconColor)));

I then use a custom Value Converter called ImageIdToUriImageSourceValueConverter to convert my image Id to the image:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var applicationUrl = App.ApplicationUrl;
    if (string.IsNullOrEmpty(value as string))
    {
        return null;
    }

    var includeColorOld = string.IsNullOrEmpty(_colorOld) ? "" : string.Format("/{0}", _colorOld);

    // I have an image api which which handles the image itself and that works fine.
    var uriString = string.Format("{0}/img/{1}/{2}{3}/{4}/{5}/{6}", applicationUrl, _x, _y, includeColorOld, _color, value, "image.png");

    return = new UriImageSource
    {
        Uri = new Uri(uriString),
        CachingEnabled = true,
        CacheValidity = new TimeSpan(30, 0, 0, 0)
    };      
}

Our Image handler uses the GUID to retrieve a svg image from our api, resizes and recolours it then returns is on the requested format e.g. png. It designed to caches the images and works very well in our websites.

My problem is that images are not caching on the mobile devices nor on the emulators. Any ideas on what I can do to solve this issues?

Thanks,

Lóan

Answer

Daniel Luberda picture Daniel Luberda · Nov 19, 2015

You could try https://github.com/molinch/FFImageLoading which is Image replacement (Android, iOS, Windows) with better caching capabilities.