Skip to content

Cache local images into memory #1279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 10, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions React/Base/RCTUtils.m
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
#import "RCTAssert.h"
#import "RCTLog.h"

static const NSUInteger RCTMaxCachableImageCount = 100;

NSString *const RCTErrorUnspecified = @"EUNSPECIFIED";

// Returns the Path of Home directory
Expand Down Expand Up @@ -829,11 +831,29 @@ BOOL RCTIsLocalAssetURL(NSURL *__nullable imageURL)
return RCTImageFromLocalAssetURL(bundleImageUrl);
}

#if TARGET_OS_OSX // [TODO(macOS GH#774)
static NSCache<NSURL *, UIImage *> *RCTLocalImageCache()
{
static NSCache *imageCache;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
imageCache = [NSCache new];
imageCache.countLimit = RCTMaxCachableImageCount;
});
return imageCache;
}
#endif // ]TODO(macOS GH#774)

UIImage *__nullable RCTImageFromLocalAssetURL(NSURL *imageURL)
{
NSString *imageName = RCTBundlePathForURL(imageURL);
#if TARGET_OS_OSX // [TODO(macOS GH#774)
NSURL *bundleImageURL = nil;

UIImage *cachedImage = [RCTLocalImageCache() objectForKey:imageURL];
if (cachedImage) {
return cachedImage;
}
#endif // ]TODO(macOS GH#774)

NSBundle *bundle = nil;
Expand Down Expand Up @@ -911,6 +931,13 @@ BOOL RCTIsLocalAssetURL(NSURL *__nullable imageURL)
}
}
}

#if TARGET_OS_OSX // [TODO(macOS GH#774)
if (image) {
[RCTLocalImageCache() setObject:image forKey:imageURL];
}
#endif // ]TODO(macOS GH#774)

return image;
}

Expand Down