SDImageCache.m 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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 "SDWebImageDecoder.h"
  10. #import "UIImage+MultiFormat.h"
  11. #import <CommonCrypto/CommonDigest.h>
  12. #import "UIImage+GIF.h"
  13. #import "NSData+ImageContentType.h"
  14. #import "NSImage+WebCache.h"
  15. // See https://github.com/rs/SDWebImage/pull/1141 for discussion
  16. @interface AutoPurgeCache : NSCache
  17. @end
  18. @implementation AutoPurgeCache
  19. - (nonnull instancetype)init {
  20. self = [super init];
  21. if (self) {
  22. #if SD_UIKIT
  23. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  24. #endif
  25. }
  26. return self;
  27. }
  28. - (void)dealloc {
  29. #if SD_UIKIT
  30. [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
  31. #endif
  32. }
  33. @end
  34. FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
  35. #if SD_MAC
  36. return image.size.height * image.size.width;
  37. #elif SD_UIKIT || SD_WATCH
  38. return image.size.height * image.size.width * image.scale * image.scale;
  39. #endif
  40. }
  41. @interface SDImageCache ()
  42. #pragma mark - Properties
  43. @property (strong, nonatomic, nonnull) NSCache *memCache;
  44. @property (strong, nonatomic, nonnull) NSString *diskCachePath;
  45. @property (strong, nonatomic, nullable) NSMutableArray<NSString *> *customPaths;
  46. @property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t ioQueue;
  47. @end
  48. @implementation SDImageCache {
  49. NSFileManager *_fileManager;
  50. }
  51. #pragma mark - Singleton, init, dealloc
  52. + (nonnull instancetype)sharedImageCache {
  53. static dispatch_once_t once;
  54. static id instance;
  55. dispatch_once(&once, ^{
  56. instance = [self new];
  57. });
  58. return instance;
  59. }
  60. - (instancetype)init {
  61. return [self initWithNamespace:@"default"];
  62. }
  63. - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns {
  64. NSString *path = [self makeDiskCachePath:ns];
  65. return [self initWithNamespace:ns diskCacheDirectory:path];
  66. }
  67. - (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
  68. diskCacheDirectory:(nonnull NSString *)directory {
  69. if ((self = [super init])) {
  70. NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
  71. // Create IO serial queue
  72. _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
  73. _config = [[SDImageCacheConfig alloc] init];
  74. // Init the memory cache
  75. _memCache = [[AutoPurgeCache alloc] init];
  76. _memCache.name = fullNamespace;
  77. // Init the disk cache
  78. if (directory != nil) {
  79. _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
  80. } else {
  81. NSString *path = [self makeDiskCachePath:ns];
  82. _diskCachePath = path;
  83. }
  84. dispatch_sync(_ioQueue, ^{
  85. _fileManager = [NSFileManager new];
  86. });
  87. #if SD_UIKIT
  88. // Subscribe to app events
  89. [[NSNotificationCenter defaultCenter] addObserver:self
  90. selector:@selector(clearMemory)
  91. name:UIApplicationDidReceiveMemoryWarningNotification
  92. object:nil];
  93. [[NSNotificationCenter defaultCenter] addObserver:self
  94. selector:@selector(deleteOldFiles)
  95. name:UIApplicationWillTerminateNotification
  96. object:nil];
  97. [[NSNotificationCenter defaultCenter] addObserver:self
  98. selector:@selector(backgroundDeleteOldFiles)
  99. name:UIApplicationDidEnterBackgroundNotification
  100. object:nil];
  101. #endif
  102. }
  103. return self;
  104. }
  105. - (void)dealloc {
  106. [[NSNotificationCenter defaultCenter] removeObserver:self];
  107. SDDispatchQueueRelease(_ioQueue);
  108. }
  109. - (void)checkIfQueueIsIOQueue {
  110. const char *currentQueueLabel = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL);
  111. const char *ioQueueLabel = dispatch_queue_get_label(self.ioQueue);
  112. if (strcmp(currentQueueLabel, ioQueueLabel) != 0) {
  113. NSLog(@"This method should be called from the ioQueue");
  114. }
  115. }
  116. #pragma mark - Cache paths
  117. - (void)addReadOnlyCachePath:(nonnull NSString *)path {
  118. if (!self.customPaths) {
  119. self.customPaths = [NSMutableArray new];
  120. }
  121. if (![self.customPaths containsObject:path]) {
  122. [self.customPaths addObject:path];
  123. }
  124. }
  125. - (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path {
  126. NSString *filename = [self cachedFileNameForKey:key];
  127. return [path stringByAppendingPathComponent:filename];
  128. }
  129. - (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key {
  130. return [self cachePathForKey:key inPath:self.diskCachePath];
  131. }
  132. - (nullable NSString *)cachedFileNameForKey:(nullable NSString *)key {
  133. const char *str = key.UTF8String;
  134. if (str == NULL) {
  135. str = "";
  136. }
  137. unsigned char r[CC_MD5_DIGEST_LENGTH];
  138. CC_MD5(str, (CC_LONG)strlen(str), r);
  139. NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
  140. r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
  141. r[11], r[12], r[13], r[14], r[15], [key.pathExtension isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", key.pathExtension]];
  142. return filename;
  143. }
  144. - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace {
  145. NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  146. return [paths[0] stringByAppendingPathComponent:fullNamespace];
  147. }
  148. #pragma mark - Store Ops
  149. - (void)storeImage:(nullable UIImage *)image
  150. forKey:(nullable NSString *)key
  151. completion:(nullable SDWebImageNoParamsBlock)completionBlock {
  152. [self storeImage:image imageData:nil forKey:key toDisk:YES completion:completionBlock];
  153. }
  154. - (void)storeImage:(nullable UIImage *)image
  155. forKey:(nullable NSString *)key
  156. toDisk:(BOOL)toDisk
  157. completion:(nullable SDWebImageNoParamsBlock)completionBlock {
  158. [self storeImage:image imageData:nil forKey:key toDisk:toDisk completion:completionBlock];
  159. }
  160. - (void)storeImage:(nullable UIImage *)image
  161. imageData:(nullable NSData *)imageData
  162. forKey:(nullable NSString *)key
  163. toDisk:(BOOL)toDisk
  164. completion:(nullable SDWebImageNoParamsBlock)completionBlock {
  165. if (!image || !key) {
  166. if (completionBlock) {
  167. completionBlock();
  168. }
  169. return;
  170. }
  171. // if memory cache is enabled
  172. if (self.config.shouldCacheImagesInMemory) {
  173. NSUInteger cost = SDCacheCostForImage(image);
  174. [self.memCache setObject:image forKey:key cost:cost];
  175. }
  176. if (toDisk) {
  177. dispatch_async(self.ioQueue, ^{
  178. @autoreleasepool {
  179. NSData *data = imageData;
  180. if (!data && image) {
  181. SDImageFormat imageFormatFromData = [NSData sd_imageFormatForImageData:data];
  182. data = [image sd_imageDataAsFormat:imageFormatFromData];
  183. }
  184. [self storeImageDataToDisk:data forKey:key];
  185. }
  186. if (completionBlock) {
  187. dispatch_async(dispatch_get_main_queue(), ^{
  188. completionBlock();
  189. });
  190. }
  191. });
  192. } else {
  193. if (completionBlock) {
  194. completionBlock();
  195. }
  196. }
  197. }
  198. - (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key {
  199. if (!imageData || !key) {
  200. return;
  201. }
  202. [self checkIfQueueIsIOQueue];
  203. if (![_fileManager fileExistsAtPath:_diskCachePath]) {
  204. [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
  205. }
  206. // get cache Path for image key
  207. NSString *cachePathForKey = [self defaultCachePathForKey:key];
  208. // transform to NSUrl
  209. NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
  210. [_fileManager createFileAtPath:cachePathForKey contents:imageData attributes:nil];
  211. // disable iCloud backup
  212. if (self.config.shouldDisableiCloud) {
  213. [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
  214. }
  215. }
  216. #pragma mark - Query and Retrieve Ops
  217. - (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
  218. dispatch_async(_ioQueue, ^{
  219. BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];
  220. // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
  221. // checking the key with and without the extension
  222. if (!exists) {
  223. exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key].stringByDeletingPathExtension];
  224. }
  225. if (completionBlock) {
  226. dispatch_async(dispatch_get_main_queue(), ^{
  227. completionBlock(exists);
  228. });
  229. }
  230. });
  231. }
  232. - (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key {
  233. return [self.memCache objectForKey:key];
  234. }
  235. - (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key {
  236. UIImage *diskImage = [self diskImageForKey:key];
  237. if (diskImage && self.config.shouldCacheImagesInMemory) {
  238. NSUInteger cost = SDCacheCostForImage(diskImage);
  239. [self.memCache setObject:diskImage forKey:key cost:cost];
  240. }
  241. return diskImage;
  242. }
  243. - (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key {
  244. // First check the in-memory cache...
  245. UIImage *image = [self imageFromMemoryCacheForKey:key];
  246. if (image) {
  247. return image;
  248. }
  249. // Second check the disk cache...
  250. image = [self imageFromDiskCacheForKey:key];
  251. return image;
  252. }
  253. - (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key {
  254. NSString *defaultPath = [self defaultCachePathForKey:key];
  255. NSData *data = [NSData dataWithContentsOfFile:defaultPath];
  256. if (data) {
  257. return data;
  258. }
  259. // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
  260. // checking the key with and without the extension
  261. data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension];
  262. if (data) {
  263. return data;
  264. }
  265. NSArray<NSString *> *customPaths = [self.customPaths copy];
  266. for (NSString *path in customPaths) {
  267. NSString *filePath = [self cachePathForKey:key inPath:path];
  268. NSData *imageData = [NSData dataWithContentsOfFile:filePath];
  269. if (imageData) {
  270. return imageData;
  271. }
  272. // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
  273. // checking the key with and without the extension
  274. imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension];
  275. if (imageData) {
  276. return imageData;
  277. }
  278. }
  279. return nil;
  280. }
  281. - (nullable UIImage *)diskImageForKey:(nullable NSString *)key {
  282. NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
  283. if (data) {
  284. UIImage *image = [UIImage sd_imageWithData:data];
  285. image = [self scaledImageForKey:key image:image];
  286. #ifdef SD_WEBP
  287. SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:data];
  288. if (imageFormat == SDImageFormatWebP) {
  289. return image;
  290. }
  291. #endif
  292. if (self.config.shouldDecompressImages) {
  293. image = [UIImage decodedImageWithImage:image];
  294. }
  295. return image;
  296. } else {
  297. return nil;
  298. }
  299. }
  300. - (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image {
  301. return SDScaledImageForKey(key, image);
  302. }
  303. - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock {
  304. if (!key) {
  305. if (doneBlock) {
  306. doneBlock(nil, nil, SDImageCacheTypeNone);
  307. }
  308. return nil;
  309. }
  310. // First check the in-memory cache...
  311. UIImage *image = [self imageFromMemoryCacheForKey:key];
  312. if (image) {
  313. NSData *diskData = nil;
  314. if ([image isGIF]) {
  315. diskData = [self diskImageDataBySearchingAllPathsForKey:key];
  316. }
  317. if (doneBlock) {
  318. doneBlock(image, diskData, SDImageCacheTypeMemory);
  319. }
  320. return nil;
  321. }
  322. NSOperation *operation = [NSOperation new];
  323. dispatch_async(self.ioQueue, ^{
  324. if (operation.isCancelled) {
  325. // do not call the completion if cancelled
  326. return;
  327. }
  328. @autoreleasepool {
  329. NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
  330. UIImage *diskImage = [self diskImageForKey:key];
  331. if (diskImage && self.config.shouldCacheImagesInMemory) {
  332. NSUInteger cost = SDCacheCostForImage(diskImage);
  333. [self.memCache setObject:diskImage forKey:key cost:cost];
  334. }
  335. if (doneBlock) {
  336. dispatch_async(dispatch_get_main_queue(), ^{
  337. doneBlock(diskImage, diskData, SDImageCacheTypeDisk);
  338. });
  339. }
  340. }
  341. });
  342. return operation;
  343. }
  344. #pragma mark - Remove Ops
  345. - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion {
  346. [self removeImageForKey:key fromDisk:YES withCompletion:completion];
  347. }
  348. - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion {
  349. if (key == nil) {
  350. return;
  351. }
  352. if (self.config.shouldCacheImagesInMemory) {
  353. [self.memCache removeObjectForKey:key];
  354. }
  355. if (fromDisk) {
  356. dispatch_async(self.ioQueue, ^{
  357. [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
  358. if (completion) {
  359. dispatch_async(dispatch_get_main_queue(), ^{
  360. completion();
  361. });
  362. }
  363. });
  364. } else if (completion){
  365. completion();
  366. }
  367. }
  368. # pragma mark - Mem Cache settings
  369. - (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
  370. self.memCache.totalCostLimit = maxMemoryCost;
  371. }
  372. - (NSUInteger)maxMemoryCost {
  373. return self.memCache.totalCostLimit;
  374. }
  375. - (NSUInteger)maxMemoryCountLimit {
  376. return self.memCache.countLimit;
  377. }
  378. - (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit {
  379. self.memCache.countLimit = maxCountLimit;
  380. }
  381. #pragma mark - Cache clean Ops
  382. - (void)clearMemory {
  383. [self.memCache removeAllObjects];
  384. }
  385. - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion {
  386. dispatch_async(self.ioQueue, ^{
  387. [_fileManager removeItemAtPath:self.diskCachePath error:nil];
  388. [_fileManager createDirectoryAtPath:self.diskCachePath
  389. withIntermediateDirectories:YES
  390. attributes:nil
  391. error:NULL];
  392. if (completion) {
  393. dispatch_async(dispatch_get_main_queue(), ^{
  394. completion();
  395. });
  396. }
  397. });
  398. }
  399. - (void)deleteOldFiles {
  400. [self deleteOldFilesWithCompletionBlock:nil];
  401. }
  402. - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock {
  403. dispatch_async(self.ioQueue, ^{
  404. NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
  405. NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
  406. // This enumerator prefetches useful properties for our cache files.
  407. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
  408. includingPropertiesForKeys:resourceKeys
  409. options:NSDirectoryEnumerationSkipsHiddenFiles
  410. errorHandler:NULL];
  411. NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.config.maxCacheAge];
  412. NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *cacheFiles = [NSMutableDictionary dictionary];
  413. NSUInteger currentCacheSize = 0;
  414. // Enumerate all of the files in the cache directory. This loop has two purposes:
  415. //
  416. // 1. Removing files that are older than the expiration date.
  417. // 2. Storing file attributes for the size-based cleanup pass.
  418. NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init];
  419. for (NSURL *fileURL in fileEnumerator) {
  420. NSError *error;
  421. NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];
  422. // Skip directories and errors.
  423. if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) {
  424. continue;
  425. }
  426. // Remove files that are older than the expiration date;
  427. NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
  428. if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
  429. [urlsToDelete addObject:fileURL];
  430. continue;
  431. }
  432. // Store a reference to this file and account for its total size.
  433. NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
  434. currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
  435. cacheFiles[fileURL] = resourceValues;
  436. }
  437. for (NSURL *fileURL in urlsToDelete) {
  438. [_fileManager removeItemAtURL:fileURL error:nil];
  439. }
  440. // If our remaining disk cache exceeds a configured maximum size, perform a second
  441. // size-based cleanup pass. We delete the oldest files first.
  442. if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
  443. // Target half of our maximum cache size for this cleanup pass.
  444. const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2;
  445. // Sort the remaining cache files by their last modification time (oldest first).
  446. NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
  447. usingComparator:^NSComparisonResult(id obj1, id obj2) {
  448. return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
  449. }];
  450. // Delete files until we fall below our desired cache size.
  451. for (NSURL *fileURL in sortedFiles) {
  452. if ([_fileManager removeItemAtURL:fileURL error:nil]) {
  453. NSDictionary<NSString *, id> *resourceValues = cacheFiles[fileURL];
  454. NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
  455. currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;
  456. if (currentCacheSize < desiredCacheSize) {
  457. break;
  458. }
  459. }
  460. }
  461. }
  462. if (completionBlock) {
  463. dispatch_async(dispatch_get_main_queue(), ^{
  464. completionBlock();
  465. });
  466. }
  467. });
  468. }
  469. #if SD_UIKIT
  470. - (void)backgroundDeleteOldFiles {
  471. Class UIApplicationClass = NSClassFromString(@"UIApplication");
  472. if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
  473. return;
  474. }
  475. UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
  476. __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  477. // Clean up any unfinished task business by marking where you
  478. // stopped or ending the task outright.
  479. [application endBackgroundTask:bgTask];
  480. bgTask = UIBackgroundTaskInvalid;
  481. }];
  482. // Start the long-running task and return immediately.
  483. [self deleteOldFilesWithCompletionBlock:^{
  484. [application endBackgroundTask:bgTask];
  485. bgTask = UIBackgroundTaskInvalid;
  486. }];
  487. }
  488. #endif
  489. #pragma mark - Cache Info
  490. - (NSUInteger)getSize {
  491. __block NSUInteger size = 0;
  492. dispatch_sync(self.ioQueue, ^{
  493. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
  494. for (NSString *fileName in fileEnumerator) {
  495. NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
  496. NSDictionary<NSString *, id> *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
  497. size += [attrs fileSize];
  498. }
  499. });
  500. return size;
  501. }
  502. - (NSUInteger)getDiskCount {
  503. __block NSUInteger count = 0;
  504. dispatch_sync(self.ioQueue, ^{
  505. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
  506. count = fileEnumerator.allObjects.count;
  507. });
  508. return count;
  509. }
  510. - (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock {
  511. NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
  512. dispatch_async(self.ioQueue, ^{
  513. NSUInteger fileCount = 0;
  514. NSUInteger totalSize = 0;
  515. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
  516. includingPropertiesForKeys:@[NSFileSize]
  517. options:NSDirectoryEnumerationSkipsHiddenFiles
  518. errorHandler:NULL];
  519. for (NSURL *fileURL in fileEnumerator) {
  520. NSNumber *fileSize;
  521. [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
  522. totalSize += fileSize.unsignedIntegerValue;
  523. fileCount += 1;
  524. }
  525. if (completionBlock) {
  526. dispatch_async(dispatch_get_main_queue(), ^{
  527. completionBlock(fileCount, totalSize);
  528. });
  529. }
  530. });
  531. }
  532. @end