RCTImageCache.m 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. /*
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import <React/RCTImageCache.h>
  8. #import <objc/runtime.h>
  9. #import <ImageIO/ImageIO.h>
  10. #import <React/RCTConvert.h>
  11. #import <React/RCTNetworking.h>
  12. #import <React/RCTUtils.h>
  13. #import <React/RCTResizeMode.h>
  14. #import <React/RCTImageUtils.h>
  15. static const NSUInteger RCTMaxCachableDecodedImageSizeInBytes = 2097152; // 2 MB
  16. static NSString *RCTCacheKeyForImage(NSString *imageTag, CGSize size, CGFloat scale,
  17. RCTResizeMode resizeMode)
  18. {
  19. return [NSString stringWithFormat:@"%@|%g|%g|%g|%lld",
  20. imageTag, size.width, size.height, scale, (long long)resizeMode];
  21. }
  22. @implementation RCTImageCache
  23. {
  24. NSOperationQueue *_imageDecodeQueue;
  25. NSCache *_decodedImageCache;
  26. NSMutableDictionary *_cacheStaleTimes;
  27. }
  28. - (instancetype)init
  29. {
  30. if (self = [super init]) {
  31. _decodedImageCache = [NSCache new];
  32. _decodedImageCache.totalCostLimit = 20 * 1024 * 1024; // 20 MB
  33. _cacheStaleTimes = [[NSMutableDictionary alloc] init];
  34. [[NSNotificationCenter defaultCenter] addObserver:self
  35. selector:@selector(clearCache)
  36. name:UIApplicationDidReceiveMemoryWarningNotification
  37. object:nil];
  38. [[NSNotificationCenter defaultCenter] addObserver:self
  39. selector:@selector(clearCache)
  40. name:UIApplicationWillResignActiveNotification
  41. object:nil];
  42. }
  43. return self;
  44. }
  45. - (void)clearCache
  46. {
  47. [_decodedImageCache removeAllObjects];
  48. @synchronized(_cacheStaleTimes) {
  49. [_cacheStaleTimes removeAllObjects];
  50. }
  51. }
  52. - (void)addImageToCache:(UIImage *)image
  53. forKey:(NSString *)cacheKey
  54. {
  55. if (!image) {
  56. return;
  57. }
  58. NSInteger bytes = image.reactDecodedImageBytes;
  59. if (bytes <= RCTMaxCachableDecodedImageSizeInBytes) {
  60. [self->_decodedImageCache setObject:image
  61. forKey:cacheKey
  62. cost:bytes];
  63. }
  64. }
  65. - (UIImage *)imageForUrl:(NSString *)url
  66. size:(CGSize)size
  67. scale:(CGFloat)scale
  68. resizeMode:(RCTResizeMode)resizeMode
  69. {
  70. NSString *cacheKey = RCTCacheKeyForImage(url, size, scale, resizeMode);
  71. @synchronized(_cacheStaleTimes) {
  72. id staleTime = _cacheStaleTimes[cacheKey];
  73. if (staleTime) {
  74. if ([[NSDate new] compare:(NSDate *)staleTime] == NSOrderedDescending) {
  75. // cached image has expired, clear it out to make room for others
  76. [_cacheStaleTimes removeObjectForKey:cacheKey];
  77. [_decodedImageCache removeObjectForKey:cacheKey];
  78. return nil;
  79. }
  80. }
  81. }
  82. return [_decodedImageCache objectForKey:cacheKey];
  83. }
  84. - (void)addImageToCache:(UIImage *)image
  85. URL:(NSString *)url
  86. size:(CGSize)size
  87. scale:(CGFloat)scale
  88. resizeMode:(RCTResizeMode)resizeMode
  89. response:(NSURLResponse *)response
  90. {
  91. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  92. NSString *cacheKey = RCTCacheKeyForImage(url, size, scale, resizeMode);
  93. BOOL shouldCache = YES;
  94. NSString *responseDate = ((NSHTTPURLResponse *)response).allHeaderFields[@"Date"];
  95. NSDate *originalDate = [self dateWithHeaderString:responseDate];
  96. NSString *cacheControl = ((NSHTTPURLResponse *)response).allHeaderFields[@"Cache-Control"];
  97. NSDate *staleTime;
  98. NSArray<NSString *> *components = [cacheControl componentsSeparatedByString:@","];
  99. for (NSString *component in components) {
  100. if ([component containsString:@"no-cache"] || [component containsString:@"no-store"] || [component hasSuffix:@"max-age=0"]) {
  101. shouldCache = NO;
  102. break;
  103. } else {
  104. NSRange range = [component rangeOfString:@"max-age="];
  105. if (range.location != NSNotFound) {
  106. NSInteger seconds = [[component substringFromIndex:range.location + range.length] integerValue];
  107. staleTime = [originalDate dateByAddingTimeInterval:(NSTimeInterval)seconds];
  108. }
  109. }
  110. }
  111. if (shouldCache) {
  112. if (!staleTime && originalDate) {
  113. NSString *expires = ((NSHTTPURLResponse *)response).allHeaderFields[@"Expires"];
  114. NSString *lastModified = ((NSHTTPURLResponse *)response).allHeaderFields[@"Last-Modified"];
  115. if (expires) {
  116. staleTime = [self dateWithHeaderString:expires];
  117. } else if (lastModified) {
  118. NSDate *lastModifiedDate = [self dateWithHeaderString:lastModified];
  119. if (lastModifiedDate) {
  120. NSTimeInterval interval = [originalDate timeIntervalSinceDate:lastModifiedDate] / 10;
  121. staleTime = [originalDate dateByAddingTimeInterval:interval];
  122. }
  123. }
  124. }
  125. if (staleTime) {
  126. @synchronized(_cacheStaleTimes) {
  127. _cacheStaleTimes[cacheKey] = staleTime;
  128. }
  129. }
  130. return [self addImageToCache:image forKey:cacheKey];
  131. }
  132. }
  133. }
  134. - (NSDate *)dateWithHeaderString:(NSString *)headerDateString {
  135. static NSDateFormatter *formatter;
  136. static dispatch_once_t onceToken;
  137. dispatch_once(&onceToken, ^{
  138. formatter = [[NSDateFormatter alloc] init];
  139. formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
  140. formatter.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
  141. formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
  142. });
  143. return [formatter dateFromString:headerDateString];
  144. }
  145. @end