SDImageCache.m 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. /*
  2. * This file is part of the SDWebImage package.
  3. * (c) Olivier Poitrey <rs@dailymotion.com>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. #import "SDImageCache.h"
  9. #import <CommonCrypto/CommonDigest.h>
  10. #import "NSImage+WebCache.h"
  11. #import "UIImage+MemoryCacheCost.h"
  12. #import "SDWebImageCodersManager.h"
  13. #define SD_MAX_FILE_EXTENSION_LENGTH (NAME_MAX - CC_MD5_DIGEST_LENGTH * 2 - 1)
  14. #define LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER);
  15. #define UNLOCK(lock) dispatch_semaphore_signal(lock);
  16. // A memory cache which auto purge the cache on memory warning and support weak cache.
  17. @interface SDMemoryCache <KeyType, ObjectType> : NSCache <KeyType, ObjectType>
  18. @end
  19. // Private
  20. @interface SDMemoryCache <KeyType, ObjectType> ()
  21. @property (nonatomic, strong, nonnull) SDImageCacheConfig *config;
  22. @property (nonatomic, strong, nonnull) NSMapTable<KeyType, ObjectType> *weakCache; // strong-weak cache
  23. @property (nonatomic, strong, nonnull) dispatch_semaphore_t weakCacheLock; // a lock to keep the access to `weakCache` thread-safe
  24. - (instancetype)init NS_UNAVAILABLE;
  25. - (instancetype)initWithConfig:(nonnull SDImageCacheConfig *)config;
  26. @end
  27. @implementation SDMemoryCache
  28. // Current this seems no use on macOS (macOS use virtual memory and do not clear cache when memory warning). So we only override on iOS/tvOS platform.
  29. // But in the future there may be more options and features for this subclass.
  30. #if SD_UIKIT
  31. - (void)dealloc {
  32. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  33. }
  34. - (instancetype)initWithConfig:(SDImageCacheConfig *)config {
  35. self = [super init];
  36. if (self) {
  37. // Use a strong-weak maptable storing the secondary cache. Follow the doc that NSCache does not copy keys
  38. // This is useful when the memory warning, the cache was purged. However, the image instance can be retained by other instance such as imageViews and alive.
  39. // At this case, we can sync weak cache back and do not need to load from disk cache
  40. self.weakCache = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
  41. self.weakCacheLock = dispatch_semaphore_create(1);
  42. self.config = config;
  43. [[NSNotificationCenter defaultCenter] addObserver:self
  44. selector:@selector(didReceiveMemoryWarning:)
  45. name:UIApplicationDidReceiveMemoryWarningNotification
  46. object:nil];
  47. }
  48. return self;
  49. }
  50. - (void)didReceiveMemoryWarning:(NSNotification *)notification {
  51. // Only remove cache, but keep weak cache
  52. [super removeAllObjects];
  53. }
  54. // `setObject:forKey:` just call this with 0 cost. Override this is enough
  55. - (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g {
  56. [super setObject:obj forKey:key cost:g];
  57. if (!self.config.shouldUseWeakMemoryCache) {
  58. return;
  59. }
  60. if (key && obj) {
  61. // Store weak cache
  62. LOCK(self.weakCacheLock);
  63. // Do the real copy of the key and only let NSMapTable manage the key's lifetime
  64. // Fixes issue #2507 https://github.com/SDWebImage/SDWebImage/issues/2507
  65. [self.weakCache setObject:obj forKey:[[key mutableCopy] copy]];
  66. UNLOCK(self.weakCacheLock);
  67. }
  68. }
  69. - (id)objectForKey:(id)key {
  70. id obj = [super objectForKey:key];
  71. if (!self.config.shouldUseWeakMemoryCache) {
  72. return obj;
  73. }
  74. if (key && !obj) {
  75. // Check weak cache
  76. LOCK(self.weakCacheLock);
  77. obj = [self.weakCache objectForKey:key];
  78. UNLOCK(self.weakCacheLock);
  79. if (obj) {
  80. // Sync cache
  81. NSUInteger cost = 0;
  82. if ([obj isKindOfClass:[UIImage class]]) {
  83. cost = [(UIImage *)obj sd_memoryCost];
  84. }
  85. [super setObject:obj forKey:key cost:cost];
  86. }
  87. }
  88. return obj;
  89. }
  90. - (void)removeObjectForKey:(id)key {
  91. [super removeObjectForKey:key];
  92. if (!self.config.shouldUseWeakMemoryCache) {
  93. return;
  94. }
  95. if (key) {
  96. // Remove weak cache
  97. LOCK(self.weakCacheLock);
  98. [self.weakCache removeObjectForKey:key];
  99. UNLOCK(self.weakCacheLock);
  100. }
  101. }
  102. - (void)removeAllObjects {
  103. [super removeAllObjects];
  104. if (!self.config.shouldUseWeakMemoryCache) {
  105. return;
  106. }
  107. // Manually remove should also remove weak cache
  108. LOCK(self.weakCacheLock);
  109. [self.weakCache removeAllObjects];
  110. UNLOCK(self.weakCacheLock);
  111. }
  112. #else
  113. - (instancetype)initWithConfig:(SDImageCacheConfig *)config {
  114. self = [super init];
  115. return self;
  116. }
  117. #endif
  118. @end
  119. @interface SDImageCache ()
  120. #pragma mark - Properties
  121. @property (strong, nonatomic, nonnull) SDMemoryCache *memCache;
  122. @property (strong, nonatomic, nonnull) NSString *diskCachePath;
  123. @property (strong, nonatomic, nullable) NSMutableArray<NSString *> *customPaths;
  124. @property (strong, nonatomic, nullable) dispatch_queue_t ioQueue;
  125. @property (strong, nonatomic, nonnull) NSFileManager *fileManager;
  126. @end
  127. @implementation SDImageCache
  128. #pragma mark - Singleton, init, dealloc
  129. + (nonnull instancetype)sharedImageCache {
  130. static dispatch_once_t once;
  131. static id instance;
  132. dispatch_once(&once, ^{
  133. instance = [self new];
  134. });
  135. return instance;
  136. }
  137. - (instancetype)init {
  138. return [self initWithNamespace:@"default"];
  139. }
  140. - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns {
  141. NSString *path = [self makeDiskCachePath:ns];
  142. return [self initWithNamespace:ns diskCacheDirectory:path];
  143. }
  144. - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
  145. diskCacheDirectory:(nonnull NSString *)directory {
  146. if ((self = [super init])) {
  147. NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
  148. // Create IO serial queue
  149. _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
  150. _config = [[SDImageCacheConfig alloc] init];
  151. // Init the memory cache
  152. _memCache = [[SDMemoryCache alloc] initWithConfig:_config];
  153. _memCache.name = fullNamespace;
  154. // Init the disk cache
  155. if (directory != nil) {
  156. _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
  157. } else {
  158. NSString *path = [self makeDiskCachePath:ns];
  159. _diskCachePath = path;
  160. }
  161. dispatch_sync(_ioQueue, ^{
  162. self.fileManager = [NSFileManager new];
  163. });
  164. #if SD_UIKIT
  165. // Subscribe to app events
  166. [[NSNotificationCenter defaultCenter] addObserver:self
  167. selector:@selector(deleteOldFiles)
  168. name:UIApplicationWillTerminateNotification
  169. object:nil];
  170. [[NSNotificationCenter defaultCenter] addObserver:self
  171. selector:@selector(backgroundDeleteOldFiles)
  172. name:UIApplicationDidEnterBackgroundNotification
  173. object:nil];
  174. #endif
  175. }
  176. return self;
  177. }
  178. - (void)dealloc {
  179. [[NSNotificationCenter defaultCenter] removeObserver:self];
  180. }
  181. #pragma mark - Cache paths
  182. - (void)addReadOnlyCachePath:(nonnull NSString *)path {
  183. if (!self.customPaths) {
  184. self.customPaths = [NSMutableArray new];
  185. }
  186. if (![self.customPaths containsObject:path]) {
  187. [self.customPaths addObject:path];
  188. }
  189. }
  190. - (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path {
  191. NSString *filename = [self cachedFileNameForKey:key];
  192. return [path stringByAppendingPathComponent:filename];
  193. }
  194. - (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key {
  195. return [self cachePathForKey:key inPath:self.diskCachePath];
  196. }
  197. - (nullable NSString *)cachedFileNameForKey:(nullable NSString *)key {
  198. const char *str = key.UTF8String;
  199. if (str == NULL) {
  200. str = "";
  201. }
  202. unsigned char r[CC_MD5_DIGEST_LENGTH];
  203. CC_MD5(str, (CC_LONG)strlen(str), r);
  204. NSURL *keyURL = [NSURL URLWithString:key];
  205. NSString *ext = keyURL ? keyURL.pathExtension : key.pathExtension;
  206. // File system has file name length limit, we need to check if ext is too long, we don't add it to the filename
  207. if (ext.length > SD_MAX_FILE_EXTENSION_LENGTH) {
  208. ext = nil;
  209. }
  210. NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
  211. r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
  212. r[11], r[12], r[13], r[14], r[15], ext.length == 0 ? @"" : [NSString stringWithFormat:@".%@", ext]];
  213. return filename;
  214. }
  215. - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace {
  216. NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  217. return [paths[0] stringByAppendingPathComponent:fullNamespace];
  218. }
  219. #pragma mark - Store Ops
  220. - (void)storeImage:(nullable UIImage *)image
  221. forKey:(nullable NSString *)key
  222. completion:(nullable SDWebImageNoParamsBlock)completionBlock {
  223. [self storeImage:image imageData:nil forKey:key toDisk:YES completion:completionBlock];
  224. }
  225. - (void)storeImage:(nullable UIImage *)image
  226. forKey:(nullable NSString *)key
  227. toDisk:(BOOL)toDisk
  228. completion:(nullable SDWebImageNoParamsBlock)completionBlock {
  229. [self storeImage:image imageData:nil forKey:key toDisk:toDisk completion:completionBlock];
  230. }
  231. - (void)storeImage:(nullable UIImage *)image
  232. imageData:(nullable NSData *)imageData
  233. forKey:(nullable NSString *)key
  234. toDisk:(BOOL)toDisk
  235. completion:(nullable SDWebImageNoParamsBlock)completionBlock {
  236. if (!image || !key) {
  237. if (completionBlock) {
  238. completionBlock();
  239. }
  240. return;
  241. }
  242. // if memory cache is enabled
  243. if (self.config.shouldCacheImagesInMemory) {
  244. NSUInteger cost = image.sd_memoryCost;
  245. [self.memCache setObject:image forKey:key cost:cost];
  246. }
  247. if (toDisk) {
  248. dispatch_async(self.ioQueue, ^{
  249. @autoreleasepool {
  250. NSData *data = imageData;
  251. if (!data && image) {
  252. // If we do not have any data to detect image format, check whether it contains alpha channel to use PNG or JPEG format
  253. SDImageFormat format;
  254. if (SDCGImageRefContainsAlpha(image.CGImage)) {
  255. format = SDImageFormatPNG;
  256. } else {
  257. format = SDImageFormatJPEG;
  258. }
  259. data = [[SDWebImageCodersManager sharedInstance] encodedDataWithImage:image format:format];
  260. }
  261. [self _storeImageDataToDisk:data forKey:key];
  262. }
  263. if (completionBlock) {
  264. dispatch_async(dispatch_get_main_queue(), ^{
  265. completionBlock();
  266. });
  267. }
  268. });
  269. } else {
  270. if (completionBlock) {
  271. completionBlock();
  272. }
  273. }
  274. }
  275. - (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key {
  276. if (!imageData || !key) {
  277. return;
  278. }
  279. dispatch_sync(self.ioQueue, ^{
  280. [self _storeImageDataToDisk:imageData forKey:key];
  281. });
  282. }
  283. // Make sure to call form io queue by caller
  284. - (void)_storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key {
  285. if (!imageData || !key) {
  286. return;
  287. }
  288. if (![self.fileManager fileExistsAtPath:_diskCachePath]) {
  289. [self.fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
  290. }
  291. // get cache Path for image key
  292. NSString *cachePathForKey = [self defaultCachePathForKey:key];
  293. // transform to NSUrl
  294. NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
  295. [imageData writeToURL:fileURL options:self.config.diskCacheWritingOptions error:nil];
  296. // disable iCloud backup
  297. if (self.config.shouldDisableiCloud) {
  298. [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  299. }
  300. }
  301. #pragma mark - Query and Retrieve Ops
  302. - (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
  303. dispatch_async(self.ioQueue, ^{
  304. BOOL exists = [self _diskImageDataExistsWithKey:key];
  305. if (completionBlock) {
  306. dispatch_async(dispatch_get_main_queue(), ^{
  307. completionBlock(exists);
  308. });
  309. }
  310. });
  311. }
  312. - (BOOL)diskImageDataExistsWithKey:(nullable NSString *)key {
  313. if (!key) {
  314. return NO;
  315. }
  316. __block BOOL exists = NO;
  317. dispatch_sync(self.ioQueue, ^{
  318. exists = [self _diskImageDataExistsWithKey:key];
  319. });
  320. return exists;
  321. }
  322. // Make sure to call form io queue by caller
  323. - (BOOL)_diskImageDataExistsWithKey:(nullable NSString *)key {
  324. if (!key) {
  325. return NO;
  326. }
  327. BOOL exists = [self.fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];
  328. // fallback because of https://github.com/SDWebImage/SDWebImage/pull/976 that added the extension to the disk file name
  329. // checking the key with and without the extension
  330. if (!exists) {
  331. exists = [self.fileManager fileExistsAtPath:[self defaultCachePathForKey:key].stringByDeletingPathExtension];
  332. }
  333. return exists;
  334. }
  335. - (nullable NSData *)diskImageDataForKey:(nullable NSString *)key {
  336. if (!key) {
  337. return nil;
  338. }
  339. __block NSData *imageData = nil;
  340. dispatch_sync(self.ioQueue, ^{
  341. imageData = [self diskImageDataBySearchingAllPathsForKey:key];
  342. });
  343. return imageData;
  344. }
  345. - (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key {
  346. return [self.memCache objectForKey:key];
  347. }
  348. - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key {
  349. UIImage *diskImage = [self diskImageForKey:key];
  350. if (diskImage && self.config.shouldCacheImagesInMemory) {
  351. NSUInteger cost = diskImage.sd_memoryCost;
  352. [self.memCache setObject:diskImage forKey:key cost:cost];
  353. }
  354. return diskImage;
  355. }
  356. - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key {
  357. // First check the in-memory cache...
  358. UIImage *image = [self imageFromMemoryCacheForKey:key];
  359. if (image) {
  360. return image;
  361. }
  362. // Second check the disk cache...
  363. image = [self imageFromDiskCacheForKey:key];
  364. return image;
  365. }
  366. - (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key {
  367. NSString *defaultPath = [self defaultCachePathForKey:key];
  368. NSData *data = [NSData dataWithContentsOfFile:defaultPath options:self.config.diskCacheReadingOptions error:nil];
  369. if (data) {
  370. return data;
  371. }
  372. // fallback because of https://github.com/SDWebImage/SDWebImage/pull/976 that added the extension to the disk file name
  373. // checking the key with and without the extension
  374. data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil];
  375. if (data) {
  376. return data;
  377. }
  378. NSArray<NSString *> *customPaths = [self.customPaths copy];
  379. for (NSString *path in customPaths) {
  380. NSString *filePath = [self cachePathForKey:key inPath:path];
  381. NSData *imageData = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil];
  382. if (imageData) {
  383. return imageData;
  384. }
  385. // fallback because of https://github.com/SDWebImage/SDWebImage/pull/976 that added the extension to the disk file name
  386. // checking the key with and without the extension
  387. imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil];
  388. if (imageData) {
  389. return imageData;
  390. }
  391. }
  392. return nil;
  393. }
  394. - (nullable UIImage *)diskImageForKey:(nullable NSString *)key {
  395. NSData *data = [self diskImageDataForKey:key];
  396. return [self diskImageForKey:key data:data];
  397. }
  398. - (nullable UIImage *)diskImageForKey:(nullable NSString *)key data:(nullable NSData *)data {
  399. return [self diskImageForKey:key data:data options:0];
  400. }
  401. - (nullable UIImage *)diskImageForKey:(nullable NSString *)key data:(nullable NSData *)data options:(SDImageCacheOptions)options {
  402. if (data) {
  403. UIImage *image = [[SDWebImageCodersManager sharedInstance] decodedImageWithData:data];
  404. image = [self scaledImageForKey:key image:image];
  405. if (self.config.shouldDecompressImages) {
  406. BOOL shouldScaleDown = options & SDImageCacheScaleDownLargeImages;
  407. image = [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&data options:@{SDWebImageCoderScaleDownLargeImagesKey: @(shouldScaleDown)}];
  408. }
  409. return image;
  410. } else {
  411. return nil;
  412. }
  413. }
  414. - (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image {
  415. return SDScaledImageForKey(key, image);
  416. }
  417. - (NSOperation *)queryCacheOperationForKey:(NSString *)key done:(SDCacheQueryCompletedBlock)doneBlock {
  418. return [self queryCacheOperationForKey:key options:0 done:doneBlock];
  419. }
  420. - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDCacheQueryCompletedBlock)doneBlock {
  421. if (!key) {
  422. if (doneBlock) {
  423. doneBlock(nil, nil, SDImageCacheTypeNone);
  424. }
  425. return nil;
  426. }
  427. // First check the in-memory cache...
  428. UIImage *image = [self imageFromMemoryCacheForKey:key];
  429. BOOL shouldQueryMemoryOnly = (image && !(options & SDImageCacheQueryDataWhenInMemory));
  430. if (shouldQueryMemoryOnly) {
  431. if (doneBlock) {
  432. doneBlock(image, nil, SDImageCacheTypeMemory);
  433. }
  434. return nil;
  435. }
  436. NSOperation *operation = [NSOperation new];
  437. void(^queryDiskBlock)(void) = ^{
  438. if (operation.isCancelled) {
  439. // do not call the completion if cancelled
  440. return;
  441. }
  442. @autoreleasepool {
  443. NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
  444. UIImage *diskImage;
  445. SDImageCacheType cacheType = SDImageCacheTypeNone;
  446. if (image) {
  447. // the image is from in-memory cache
  448. diskImage = image;
  449. cacheType = SDImageCacheTypeMemory;
  450. } else if (diskData) {
  451. cacheType = SDImageCacheTypeDisk;
  452. // decode image data only if in-memory cache missed
  453. diskImage = [self diskImageForKey:key data:diskData options:options];
  454. if (diskImage && self.config.shouldCacheImagesInMemory) {
  455. NSUInteger cost = diskImage.sd_memoryCost;
  456. [self.memCache setObject:diskImage forKey:key cost:cost];
  457. }
  458. }
  459. if (doneBlock) {
  460. if (options & SDImageCacheQueryDiskSync) {
  461. doneBlock(diskImage, diskData, cacheType);
  462. } else {
  463. dispatch_async(dispatch_get_main_queue(), ^{
  464. doneBlock(diskImage, diskData, cacheType);
  465. });
  466. }
  467. }
  468. }
  469. };
  470. if (options & SDImageCacheQueryDiskSync) {
  471. queryDiskBlock();
  472. } else {
  473. dispatch_async(self.ioQueue, queryDiskBlock);
  474. }
  475. return operation;
  476. }
  477. #pragma mark - Remove Ops
  478. - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion {
  479. [self removeImageForKey:key fromDisk:YES withCompletion:completion];
  480. }
  481. - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion {
  482. if (key == nil) {
  483. return;
  484. }
  485. if (self.config.shouldCacheImagesInMemory) {
  486. [self.memCache removeObjectForKey:key];
  487. }
  488. if (fromDisk) {
  489. dispatch_async(self.ioQueue, ^{
  490. [self.fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
  491. if (completion) {
  492. dispatch_async(dispatch_get_main_queue(), ^{
  493. completion();
  494. });
  495. }
  496. });
  497. } else if (completion){
  498. completion();
  499. }
  500. }
  501. # pragma mark - Mem Cache settings
  502. - (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
  503. self.memCache.totalCostLimit = maxMemoryCost;
  504. }
  505. - (NSUInteger)maxMemoryCost {
  506. return self.memCache.totalCostLimit;
  507. }
  508. - (NSUInteger)maxMemoryCountLimit {
  509. return self.memCache.countLimit;
  510. }
  511. - (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit {
  512. self.memCache.countLimit = maxCountLimit;
  513. }
  514. #pragma mark - Cache clean Ops
  515. - (void)clearMemory {
  516. [self.memCache removeAllObjects];
  517. }
  518. - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion {
  519. dispatch_async(self.ioQueue, ^{
  520. [self.fileManager removeItemAtPath:self.diskCachePath error:nil];
  521. [self.fileManager createDirectoryAtPath:self.diskCachePath
  522. withIntermediateDirectories:YES
  523. attributes:nil
  524. error:NULL];
  525. if (completion) {
  526. dispatch_async(dispatch_get_main_queue(), ^{
  527. completion();
  528. });
  529. }
  530. });
  531. }
  532. - (void)deleteOldFiles {
  533. [self deleteOldFilesWithCompletionBlock:nil];
  534. }
  535. - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock {
  536. dispatch_async(self.ioQueue, ^{
  537. NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
  538. // Compute content date key to be used for tests
  539. NSURLResourceKey cacheContentDateKey = NSURLContentModificationDateKey;
  540. switch (self.config.diskCacheExpireType) {
  541. case SDImageCacheConfigExpireTypeAccessDate:
  542. cacheContentDateKey = NSURLContentAccessDateKey;
  543. break;
  544. case SDImageCacheConfigExpireTypeModificationDate:
  545. cacheContentDateKey = NSURLContentModificationDateKey;
  546. break;
  547. default:
  548. break;
  549. }
  550. NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, cacheContentDateKey, NSURLTotalFileAllocatedSizeKey];
  551. // This enumerator prefetches useful properties for our cache files.
  552. NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL
  553. includingPropertiesForKeys:resourceKeys
  554. options:NSDirectoryEnumerationSkipsHiddenFiles
  555. errorHandler:NULL];
  556. NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.config.maxCacheAge];
  557. NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *cacheFiles = [NSMutableDictionary dictionary];
  558. NSUInteger currentCacheSize = 0;
  559. // Enumerate all of the files in the cache directory. This loop has two purposes:
  560. //
  561. // 1. Removing files that are older than the expiration date.
  562. // 2. Storing file attributes for the size-based cleanup pass.
  563. NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init];
  564. for (NSURL *fileURL in fileEnumerator) {
  565. NSError *error;
  566. NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];
  567. // Skip directories and errors.
  568. if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) {
  569. continue;
  570. }
  571. // Remove files that are older than the expiration date;
  572. NSDate *modifiedDate = resourceValues[cacheContentDateKey];
  573. if ([[modifiedDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
  574. [urlsToDelete addObject:fileURL];
  575. continue;
  576. }
  577. // Store a reference to this file and account for its total size.
  578. NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
  579. currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
  580. cacheFiles[fileURL] = resourceValues;
  581. }
  582. for (NSURL *fileURL in urlsToDelete) {
  583. [self.fileManager removeItemAtURL:fileURL error:nil];
  584. }
  585. // If our remaining disk cache exceeds a configured maximum size, perform a second
  586. // size-based cleanup pass. We delete the oldest files first.
  587. if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
  588. // Target half of our maximum cache size for this cleanup pass.
  589. const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2;
  590. // Sort the remaining cache files by their last modification time or last access time (oldest first).
  591. NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
  592. usingComparator:^NSComparisonResult(id obj1, id obj2) {
  593. return [obj1[cacheContentDateKey] compare:obj2[cacheContentDateKey]];
  594. }];
  595. // Delete files until we fall below our desired cache size.
  596. for (NSURL *fileURL in sortedFiles) {
  597. if ([self.fileManager removeItemAtURL:fileURL error:nil]) {
  598. NSDictionary<NSString *, id> *resourceValues = cacheFiles[fileURL];
  599. NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
  600. currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;
  601. if (currentCacheSize < desiredCacheSize) {
  602. break;
  603. }
  604. }
  605. }
  606. }
  607. if (completionBlock) {
  608. dispatch_async(dispatch_get_main_queue(), ^{
  609. completionBlock();
  610. });
  611. }
  612. });
  613. }
  614. #if SD_UIKIT
  615. - (void)backgroundDeleteOldFiles {
  616. Class UIApplicationClass = NSClassFromString(@"UIApplication");
  617. if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
  618. return;
  619. }
  620. UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
  621. __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  622. // Clean up any unfinished task business by marking where you
  623. // stopped or ending the task outright.
  624. [application endBackgroundTask:bgTask];
  625. bgTask = UIBackgroundTaskInvalid;
  626. }];
  627. // Start the long-running task and return immediately.
  628. [self deleteOldFilesWithCompletionBlock:^{
  629. [application endBackgroundTask:bgTask];
  630. bgTask = UIBackgroundTaskInvalid;
  631. }];
  632. }
  633. #endif
  634. #pragma mark - Cache Info
  635. - (NSUInteger)getSize {
  636. __block NSUInteger size = 0;
  637. dispatch_sync(self.ioQueue, ^{
  638. NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtPath:self.diskCachePath];
  639. for (NSString *fileName in fileEnumerator) {
  640. NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
  641. NSDictionary<NSString *, id> *attrs = [self.fileManager attributesOfItemAtPath:filePath error:nil];
  642. size += [attrs fileSize];
  643. }
  644. });
  645. return size;
  646. }
  647. - (NSUInteger)getDiskCount {
  648. __block NSUInteger count = 0;
  649. dispatch_sync(self.ioQueue, ^{
  650. NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtPath:self.diskCachePath];
  651. count = fileEnumerator.allObjects.count;
  652. });
  653. return count;
  654. }
  655. - (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock {
  656. NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
  657. dispatch_async(self.ioQueue, ^{
  658. NSUInteger fileCount = 0;
  659. NSUInteger totalSize = 0;
  660. NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL
  661. includingPropertiesForKeys:@[NSFileSize]
  662. options:NSDirectoryEnumerationSkipsHiddenFiles
  663. errorHandler:NULL];
  664. for (NSURL *fileURL in fileEnumerator) {
  665. NSNumber *fileSize;
  666. [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
  667. totalSize += fileSize.unsignedIntegerValue;
  668. fileCount += 1;
  669. }
  670. if (completionBlock) {
  671. dispatch_async(dispatch_get_main_queue(), ^{
  672. completionBlock(fileCount, totalSize);
  673. });
  674. }
  675. });
  676. }
  677. @end