6

So I'm using Coil image loading library to load images from an API by specifying the image URL. However when there is no internet connection I want to be able to see those images in my app. Is there any support for that kind of thing in Coil library or we should store those images locally by ourselves?

And if so, should we convert that image URL to bitmap using Coil and then save it locally?

UPDATE:

I'm using the library with Jetpack Compose btw.

 val painter = rememberImagePainter("$BASE_URL${item.image}") {
        memoryCachePolicy(policy = CachePolicy.ENABLED)
    }
Stefan
  • 2,829
  • 5
  • 20
  • 44
  • Seems that you want to cache images with Coil. https://coil-kt.github.io/coil/getting_started/#memory-cache – shrimpcolo Sep 28 '21 at 10:49
  • 1
    @tancolo They say that by default disk caching is enabled, but how come that when my internet is not available I don't see the images? – Stefan Sep 28 '21 at 11:10

2 Answers2

9

Coil does cache the images on the disk of the device to be able to use them offline but only when the response header of the image request includes cache control headers that allow Coil to do that. The reason for that is that Coil uses disk cache provided by OkHttp and not an own cache implementation.

Check the response header of the image request and look for headers like Cache-Control: no-cache, no-store, max-age=0, must-revalidate, ... and/or Pragma: no-cache (For all cache control headers see: Cache-Control MDN Web docs)

If one these is present OkHttp will not store the response on the disk cache. You can solve this by changing the api configuration to allow caching of images (if you have access to that) or providing a OkHttp interceptor that changes the response header. See: Interceptors: Rewriting Responses

Aburg
  • 246
  • 1
  • 6
  • 1
    Wow! Thank you man, I've added Cache-Control header and it works. Didn't know about that type of header yet. :) – Stefan Oct 02 '21 at 17:09
1

You can handle customise your imageloader with cache options, enabling memory or disk cachePolicy as required can handle cache/no-internet cases.

Currently you are not enabling disk policy, so you wont be able to handle no-internet cases in fresh app start, adding that will solve image loading from cache in no-internet case.

val imgLoader = ImageLoader.Builder(context)
                .memoryCachePolicy(CachePolicy.ENABLED)
                .diskCachePolicy(CachePolicy.ENABLED)
                .build()
image.load(url, imgLoader)

Same for compose, can pass this imageLoader in AsyncImage Composable

shubham chouhan
  • 580
  • 7
  • 8