react-native-fast-image icon indicating copy to clipboard operation
react-native-fast-image copied to clipboard

how do i find out if a file exists in cache?

Open lucasvieceli opened this issue 4 years ago • 6 comments

how do i find out if a file exists in cache?

lucasvieceli avatar Sep 27 '21 13:09 lucasvieceli

@lucasvieceli I wrote a patch that includes the following method:

iOS

RCT_EXPORT_METHOD(getCachePathForKey:(nonnull NSString *)key
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
    SDDiskCache *diskCache = [[SDImageCache sharedImageCache] diskCache];
    if (diskCache == nil) {
        resolve(nil);
    }
    @try {
        NSString* path = [diskCache cachePathForKey:key];
        resolve(path);
    } @catch (NSException *exception) {
        reject(@"disk_cache_path_for_key_failure", @"An error occurred while reading the path for this item in the cache.", nil);
    }
}

Android

@ReactMethod
public void getCachePathForKey(final String key, final Promise promise) {
   File file = Glide.with(activity).asFile().load(url).submit().get()
   // resolve path of file
}

JS API

In the JS side, this looks like:

const path = await FastImage.getCachePathForKey(myImageUrl);
if (!path) {
  // cache could not associate that item to a path.
  // item may not be in cache.
}

Notes

For any given file in the cache, you'll need to know the key. Currently, react-native-fast-image doesn't allow you to provide a custom cache key when an image is stored in the cache. However, we can get close to figuring out the cache key for a given file for remote files (i.e. images that are loaded via URL).

If you are wanting to find a cached copy of a remote file (i.e. https://my-website.com/my-image.png), the cache key is the URL (:warning: query parameters are removed from the cache key by default on iOS. If you want your key to include the query parameters, you'll need to patch the library).

Hope this helps!

matthamil avatar Nov 17 '21 17:11 matthamil

Thanks @matthamil

joshuamyers-dev avatar Dec 08 '21 01:12 joshuamyers-dev

@matthamil I added the code to the FFFastImageViewManager.m file and rebuilt my project but my RN project couldn't find that function. Is there anything that I missed to be able to call getCachePathForKey ?

babyrusa avatar Jan 29 '22 20:01 babyrusa

@babyrusa I can't really give a helpful answer without access to your code. My code snippets will likely need to be adjusted to your specific needs, but the APIs they use internally should get you on the right track.

matthamil avatar Jan 29 '22 21:01 matthamil

#877

ameer-taghavi avatar Feb 18 '22 11:02 ameer-taghavi