SDImageCache.m 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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. if (self.config.shouldDecompressImages) {
  287. image = [UIImage decodedImageWithImage:image];
  288. }
  289. return image;
  290. } else {
  291. return nil;
  292. }
  293. }
  294. - (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image {
  295. return SDScaledImageForKey(key, image);
  296. }
  297. - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock {
  298. if (!key) {
  299. if (doneBlock) {
  300. doneBlock(nil, nil, SDImageCacheTypeNone);
  301. }
  302. return nil;
  303. }
  304. // First check the in-memory cache...
  305. UIImage *image = [self imageFromMemoryCacheForKey:key];
  306. if (image) {
  307. NSData *diskData = nil;
  308. if ([image isGIF]) {
  309. diskData = [self diskImageDataBySearchingAllPathsForKey:key];
  310. }
  311. if (doneBlock) {
  312. doneBlock(image, diskData, SDImageCacheTypeMemory);
  313. }
  314. return nil;
  315. }
  316. NSOperation *operation = [NSOperation new];
  317. dispatch_async(self.ioQueue, ^{
  318. if (operation.isCancelled) {
  319. // do not call the completion if cancelled
  320. return;
  321. }
  322. @autoreleasepool {
  323. NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
  324. UIImage *diskImage = [self diskImageForKey:key];
  325. if (diskImage && self.config.shouldCacheImagesInMemory) {
  326. NSUInteger cost = SDCacheCostForImage(diskImage);
  327. [self.memCache setObject:diskImage forKey:key cost:cost];
  328. }
  329. if (doneBlock) {
  330. dispatch_async(dispatch_get_main_queue(), ^{
  331. doneBlock(diskImage, diskData, SDImageCacheTypeDisk);
  332. });
  333. }
  334. }
  335. });
  336. return operation;
  337. }
  338. #pragma mark - Remove Ops
  339. - (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion {
  340. [self removeImageForKey:key fromDisk:YES withCompletion:completion];
  341. }
  342. - (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion {
  343. if (key == nil) {
  344. return;
  345. }
  346. if (self.config.shouldCacheImagesInMemory) {
  347. [self.memCache removeObjectForKey:key];
  348. }
  349. if (fromDisk) {
  350. dispatch_async(self.ioQueue, ^{
  351. [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
  352. if (completion) {
  353. dispatch_async(dispatch_get_main_queue(), ^{
  354. completion();
  355. });
  356. }
  357. });
  358. } else if (completion){
  359. completion();
  360. }
  361. }
  362. # pragma mark - Mem Cache settings
  363. - (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
  364. self.memCache.totalCostLimit = maxMemoryCost;
  365. }
  366. - (NSUInteger)maxMemoryCost {
  367. return self.memCache.totalCostLimit;
  368. }
  369. - (NSUInteger)maxMemoryCountLimit {
  370. return self.memCache.countLimit;
  371. }
  372. - (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit {
  373. self.memCache.countLimit = maxCountLimit;
  374. }
  375. #pragma mark - Cache clean Ops
  376. - (void)clearMemory {
  377. [self.memCache removeAllObjects];
  378. }
  379. - (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion {
  380. dispatch_async(self.ioQueue, ^{
  381. [_fileManager removeItemAtPath:self.diskCachePath error:nil];
  382. [_fileManager createDirectoryAtPath:self.diskCachePath
  383. withIntermediateDirectories:YES
  384. attributes:nil
  385. error:NULL];
  386. if (completion) {
  387. dispatch_async(dispatch_get_main_queue(), ^{
  388. completion();
  389. });
  390. }
  391. });
  392. }
  393. - (void)deleteOldFiles {
  394. [self deleteOldFilesWithCompletionBlock:nil];
  395. }
  396. - (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock {
  397. dispatch_async(self.ioQueue, ^{
  398. NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
  399. NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
  400. // This enumerator prefetches useful properties for our cache files.
  401. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
  402. includingPropertiesForKeys:resourceKeys
  403. options:NSDirectoryEnumerationSkipsHiddenFiles
  404. errorHandler:NULL];
  405. NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.config.maxCacheAge];
  406. NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *cacheFiles = [NSMutableDictionary dictionary];
  407. NSUInteger currentCacheSize = 0;
  408. // Enumerate all of the files in the cache directory. This loop has two purposes:
  409. //
  410. // 1. Removing files that are older than the expiration date.
  411. // 2. Storing file attributes for the size-based cleanup pass.
  412. NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init];
  413. for (NSURL *fileURL in fileEnumerator) {
  414. NSError *error;
  415. NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];
  416. // Skip directories and errors.
  417. if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) {
  418. continue;
  419. }
  420. // Remove files that are older than the expiration date;
  421. NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
  422. if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
  423. [urlsToDelete addObject:fileURL];
  424. continue;
  425. }
  426. // Store a reference to this file and account for its total size.
  427. NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
  428. currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
  429. cacheFiles[fileURL] = resourceValues;
  430. }
  431. for (NSURL *fileURL in urlsToDelete) {
  432. [_fileManager removeItemAtURL:fileURL error:nil];
  433. }
  434. // If our remaining disk cache exceeds a configured maximum size, perform a second
  435. // size-based cleanup pass. We delete the oldest files first.
  436. if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
  437. // Target half of our maximum cache size for this cleanup pass.
  438. const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2;
  439. // Sort the remaining cache files by their last modification time (oldest first).
  440. NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
  441. usingComparator:^NSComparisonResult(id obj1, id obj2) {
  442. return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
  443. }];
  444. // Delete files until we fall below our desired cache size.
  445. for (NSURL *fileURL in sortedFiles) {
  446. if ([_fileManager removeItemAtURL:fileURL error:nil]) {
  447. NSDictionary<NSString *, id> *resourceValues = cacheFiles[fileURL];
  448. NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
  449. currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;
  450. if (currentCacheSize < desiredCacheSize) {
  451. break;
  452. }
  453. }
  454. }
  455. }
  456. if (completionBlock) {
  457. dispatch_async(dispatch_get_main_queue(), ^{
  458. completionBlock();
  459. });
  460. }
  461. });
  462. }
  463. #if SD_UIKIT
  464. - (void)backgroundDeleteOldFiles {
  465. Class UIApplicationClass = NSClassFromString(@"UIApplication");
  466. if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
  467. return;
  468. }
  469. UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
  470. __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
  471. // Clean up any unfinished task business by marking where you
  472. // stopped or ending the task outright.
  473. [application endBackgroundTask:bgTask];
  474. bgTask = UIBackgroundTaskInvalid;
  475. }];
  476. // Start the long-running task and return immediately.
  477. [self deleteOldFilesWithCompletionBlock:^{
  478. [application endBackgroundTask:bgTask];
  479. bgTask = UIBackgroundTaskInvalid;
  480. }];
  481. }
  482. #endif
  483. #pragma mark - Cache Info
  484. - (NSUInteger)getSize {
  485. __block NSUInteger size = 0;
  486. dispatch_sync(self.ioQueue, ^{
  487. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
  488. for (NSString *fileName in fileEnumerator) {
  489. NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
  490. NSDictionary<NSString *, id> *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
  491. size += [attrs fileSize];
  492. }
  493. });
  494. return size;
  495. }
  496. - (NSUInteger)getDiskCount {
  497. __block NSUInteger count = 0;
  498. dispatch_sync(self.ioQueue, ^{
  499. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
  500. count = fileEnumerator.allObjects.count;
  501. });
  502. return count;
  503. }
  504. - (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock {
  505. NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
  506. dispatch_async(self.ioQueue, ^{
  507. NSUInteger fileCount = 0;
  508. NSUInteger totalSize = 0;
  509. NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
  510. includingPropertiesForKeys:@[NSFileSize]
  511. options:NSDirectoryEnumerationSkipsHiddenFiles
  512. errorHandler:NULL];
  513. for (NSURL *fileURL in fileEnumerator) {
  514. NSNumber *fileSize;
  515. [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
  516. totalSize += fileSize.unsignedIntegerValue;
  517. fileCount += 1;
  518. }
  519. if (completionBlock) {
  520. dispatch_async(dispatch_get_main_queue(), ^{
  521. completionBlock(fileCount, totalSize);
  522. });
  523. }
  524. });
  525. }
  526. @end