mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
fix(iOS): reuse prefetched images (#57971)
Summary: Fixes https://github.com/react/react-native/issues/28557. iOS image prefetch stores decoded images using their original-size cache key. Later image requests often include concrete dimensions, producing a different cache key and causing the prefetched image to be downloaded again. This change falls back to the original-size cache entry for sized requests and reports prefetched decoded images as available in memory through `Image.queryCache()`. ## Changelog: [IOS] [FIXED] - Reuse prefetched images for subsequent sized image requests Pull Request resolved: https://github.com/react/react-native/pull/57971 Test Plan: - `git diff --check` — passed. - Tested with RNTester on an iPhone simulator running iOS 26.5. - Opened **Image → Image Loading Events**. - Verified `Image.prefetch()` completed successfully. - Verified `Image.queryCache()` returned `disk/memory`. - Verified the prefetched image loaded and rendered at the requested dimensions without unexpected stretching, cropping, or distortion. Screenshot: <img width="318" height="604" alt="Screenshot 2026-08-16 at 12 09 30 PM" src="https://github.com/user-attachments/assets/c6db4ce4-d130-47d3-ae64-0a62f5e5385e" /> Reviewed By: cipolleschi Differential Revision: D118334375 Pulled By: javache fbshipit-source-id: 3ed64fdde88beb3476056fb0f4ac5acc294ce4ae
This commit is contained in:
1 parent
665beff9df
commit
0e87de0fd9
2 files changed
+142
-20
No files matched your search
@@ -186,19 +186,25 @@ RCT_EXPORT_MODULE()
|
||||
|
||||
- (id<RCTImageCache>)imageCache
|
||||
{
|
||||
if (!_imageCache) {
|
||||
// set up with default cache
|
||||
_imageCache = [RCTImageCache new];
|
||||
// Callers reach this from the URL request queue, the JS thread and the main
|
||||
// queue, so the lazy initialization has to be serialized.
|
||||
@synchronized(self) {
|
||||
if (_imageCache == nil) {
|
||||
// set up with default cache
|
||||
_imageCache = [RCTImageCache new];
|
||||
}
|
||||
return _imageCache;
|
||||
}
|
||||
return _imageCache;
|
||||
}
|
||||
|
||||
- (void)setImageCache:(id<RCTImageCache>)cache
|
||||
{
|
||||
if (_imageCache) {
|
||||
RCTLogWarn(@"RCTImageCache was already set and has now been overridden.");
|
||||
@synchronized(self) {
|
||||
if (_imageCache != nil) {
|
||||
RCTLogWarn(@"RCTImageCache was already set and has now been overridden.");
|
||||
}
|
||||
_imageCache = cache;
|
||||
}
|
||||
_imageCache = cache;
|
||||
}
|
||||
|
||||
- (id<RCTImageURLLoader>)imageURLLoaderForURL:(NSURL *)URL
|
||||
@@ -311,6 +317,28 @@ static UIImage *RCTResizeImageIfNeeded(UIImage *image, CGSize size, CGFloat scal
|
||||
return image;
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks up a decoded image, falling back to the original-size entry that
|
||||
* prefetching writes so that a request for concrete dimensions can reuse it.
|
||||
* The fallback key must stay in sync with the one used by
|
||||
* prefetchImageWithMetadata:queryRootName:rootTag:resolve:reject:.
|
||||
*/
|
||||
static UIImage *RCTCachedImageForURL(
|
||||
id<RCTImageCache> imageCache,
|
||||
NSString *urlString,
|
||||
CGSize size,
|
||||
CGFloat scale,
|
||||
BOOL clipped,
|
||||
RCTResizeMode resizeMode)
|
||||
{
|
||||
UIImage *image = [imageCache imageForUrl:urlString size:size scale:scale resizeMode:resizeMode];
|
||||
if (image != nil) {
|
||||
return image;
|
||||
}
|
||||
image = [imageCache imageForUrl:urlString size:CGSizeZero scale:1 resizeMode:RCTResizeModeStretch];
|
||||
return clipped ? RCTResizeImageIfNeeded(image, size, scale, resizeMode) : image;
|
||||
}
|
||||
|
||||
/*
|
||||
* This function abstracts away the migration from loadImageForURL to loadImageURL by handling checking whether
|
||||
* the interface responds to the new function signature and calling the appropriate function based on the result.
|
||||
@@ -492,6 +520,7 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
|
||||
- (RCTImageURLLoaderRequest *)_loadImageOrDataWithURLRequest:(NSURLRequest *)request
|
||||
size:(CGSize)size
|
||||
scale:(CGFloat)scale
|
||||
clipped:(BOOL)clipped
|
||||
resizeMode:(RCTResizeMode)resizeMode
|
||||
priority:(RCTImageLoaderPriority)priority
|
||||
attribution:(const ImageURLLoaderAttribution &)attribution
|
||||
@@ -542,10 +571,8 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
|
||||
}
|
||||
|
||||
if (cacheResult && partialLoadHandler) {
|
||||
UIImage *image = [[self imageCache] imageForUrl:request.URL.absoluteString
|
||||
size:size
|
||||
scale:scale
|
||||
resizeMode:resizeMode];
|
||||
UIImage *image =
|
||||
RCTCachedImageForURL([self imageCache], request.URL.absoluteString, size, scale, clipped, resizeMode);
|
||||
if (image) {
|
||||
partialLoadHandler(image);
|
||||
}
|
||||
@@ -662,10 +689,8 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
|
||||
} else {
|
||||
UIImage *image;
|
||||
if (cacheResult) {
|
||||
image = [[strongSelf imageCache] imageForUrl:request.URL.absoluteString
|
||||
size:size
|
||||
scale:scale
|
||||
resizeMode:resizeMode];
|
||||
image = RCTCachedImageForURL(
|
||||
[strongSelf imageCache], request.URL.absoluteString, size, scale, clipped, resizeMode);
|
||||
}
|
||||
|
||||
if (image) {
|
||||
@@ -889,6 +914,7 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
|
||||
RCTImageURLLoaderRequest *loaderRequest = [self _loadImageOrDataWithURLRequest:imageURLRequest
|
||||
size:size
|
||||
scale:scale
|
||||
clipped:clipped
|
||||
resizeMode:resizeMode
|
||||
priority:priority
|
||||
attribution:attribution
|
||||
@@ -1107,6 +1133,7 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
|
||||
RCTImageURLLoaderRequest *loaderRequest = [self _loadImageOrDataWithURLRequest:imageURLRequest
|
||||
size:CGSizeZero
|
||||
scale:1
|
||||
clipped:NO
|
||||
resizeMode:RCTResizeModeStretch
|
||||
priority:RCTImageLoaderPriorityImmediate
|
||||
attribution:{}
|
||||
@@ -1121,18 +1148,22 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
|
||||
NSMutableDictionary *results = [NSMutableDictionary dictionary];
|
||||
for (id request in requests) {
|
||||
NSURLRequest *urlRequest = [RCTConvert NSURLRequest:request];
|
||||
if (urlRequest) {
|
||||
NSString *urlString = urlRequest.URL.absoluteString;
|
||||
if (urlRequest != nil && urlString != nil) {
|
||||
NSCachedURLResponse *cachedResponse = [NSURLCache.sharedURLCache cachedResponseForRequest:urlRequest];
|
||||
if (cachedResponse) {
|
||||
if (cachedResponse.storagePolicy == NSURLCacheStorageAllowedInMemoryOnly) {
|
||||
results[urlRequest.URL.absoluteString] = @"memory";
|
||||
results[urlString] = @"memory";
|
||||
} else if (NSURLCache.sharedURLCache.currentMemoryUsage == 0) {
|
||||
// We can't check whether the file is cached on disk or memory.
|
||||
// However, if currentMemoryUsage is disabled, it must be read from disk.
|
||||
results[urlRequest.URL.absoluteString] = @"disk";
|
||||
results[urlString] = @"disk";
|
||||
} else {
|
||||
results[urlRequest.URL.absoluteString] = @"disk/memory";
|
||||
results[urlString] = @"disk/memory";
|
||||
}
|
||||
} else if (
|
||||
[[self imageCache] imageForUrl:urlString size:CGSizeZero scale:1 resizeMode:RCTResizeModeStretch] != nil) {
|
||||
results[urlString] = @"memory";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,98 @@ unsigned char blackGIF[] = {0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01
|
||||
RCTDefineImageURLLoader(RCTImageLoaderTestsURLLoader1) RCTDefineImageURLLoader(RCTImageLoaderTestsURLLoader2)
|
||||
RCTDefineImageDecoder(RCTImageLoaderTestsDecoder1) RCTDefineImageDecoder(RCTImageLoaderTestsDecoder2)
|
||||
|
||||
@interface RCTImageLoaderTests : XCTestCase
|
||||
@interface RCTImageLoaderTestsImageCache : NSObject <RCTImageCache>
|
||||
|
||||
@property (nonatomic, strong) UIImage *image;
|
||||
@property (nonatomic, copy) NSString *URLString;
|
||||
@property (nonatomic, assign) CGSize requestedSize;
|
||||
@property (nonatomic, assign) BOOL didMissRequestedSize;
|
||||
@property (nonatomic, assign) BOOL didHitOriginalSize;
|
||||
|
||||
@end
|
||||
|
||||
@implementation RCTImageLoaderTestsImageCache
|
||||
|
||||
- (UIImage *)imageForUrl:(NSString *)url
|
||||
size:(CGSize)size
|
||||
scale:(CGFloat)scale
|
||||
resizeMode:(RCTResizeMode)resizeMode
|
||||
{
|
||||
if (![url isEqualToString:self.URLString] || scale != 1 || resizeMode != RCTResizeModeStretch) {
|
||||
return nil;
|
||||
}
|
||||
if (CGSizeEqualToSize(size, self.requestedSize)) {
|
||||
self.didMissRequestedSize = YES;
|
||||
return nil;
|
||||
}
|
||||
if (CGSizeEqualToSize(size, CGSizeZero)) {
|
||||
self.didHitOriginalSize = YES;
|
||||
return self.image;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (void)addImageToCache:(__unused UIImage *)image
|
||||
URL:(__unused NSString *)url
|
||||
size:(__unused CGSize)size
|
||||
scale:(__unused CGFloat)scale
|
||||
resizeMode:(__unused RCTResizeMode)resizeMode
|
||||
response:(__unused NSURLResponse *)response
|
||||
{
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@interface RCTImageLoaderCacheTests : XCTestCase
|
||||
|
||||
@end
|
||||
|
||||
@implementation RCTImageLoaderCacheTests
|
||||
|
||||
- (void)testCachedImagePreservesNaturalSizeWhenNotClipped
|
||||
{
|
||||
CGSize imageSize = CGSizeMake(200, 100);
|
||||
UIGraphicsBeginImageContextWithOptions(imageSize, YES, 1);
|
||||
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
|
||||
UIGraphicsEndImageContext();
|
||||
|
||||
RCTImageLoaderTestsImageCache *imageCache = [RCTImageLoaderTestsImageCache new];
|
||||
imageCache.image = image;
|
||||
imageCache.URLString = @"https://reactnative.dev/img/opengraph.png";
|
||||
imageCache.requestedSize = CGSizeMake(100, 100);
|
||||
|
||||
NS_VALID_UNTIL_END_OF_SCOPE RCTImageLoader *imageLoader = [[RCTImageLoader alloc]
|
||||
initWithRedirectDelegate:nil
|
||||
loadersProvider:^NSArray<id<RCTImageURLLoader>> *(__unused RCTModuleRegistry *moduleRegistry) {
|
||||
return @[];
|
||||
}
|
||||
decodersProvider:^NSArray<id<RCTImageDataDecoder>> *(__unused RCTModuleRegistry *moduleRegistry) {
|
||||
return @[];
|
||||
}];
|
||||
[imageLoader setImageCache:imageCache];
|
||||
|
||||
XCTestExpectation *expectation = [self expectationWithDescription:@"Image loaded from cache"];
|
||||
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageCache.URLString]];
|
||||
[imageLoader loadImageWithURLRequest:request
|
||||
size:imageCache.requestedSize
|
||||
scale:1
|
||||
clipped:NO
|
||||
resizeMode:RCTResizeModeStretch
|
||||
progressBlock:nil
|
||||
partialLoadBlock:nil
|
||||
completionBlock:^(NSError *error, UIImage *loadedImage) {
|
||||
XCTAssertNil(error);
|
||||
XCTAssertEqualObjects(loadedImage, image);
|
||||
[expectation fulfill];
|
||||
}];
|
||||
[self waitForExpectations:@[ expectation ] timeout:1];
|
||||
XCTAssertTrue(imageCache.didMissRequestedSize);
|
||||
XCTAssertTrue(imageCache.didHitOriginalSize);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@interface RCTImageLoaderTests : XCTestCase
|
||||
|
||||
@end
|
||||
|
||||
|
||||
Reference in new issue
Block a user