From 18334bcc8f298125a67cf35f39c25bdcc155128f Mon Sep 17 00:00:00 2001 From: Jon Parise Date: Tue, 25 Jun 2013 19:25:04 -0700 Subject: [PATCH] Add -calculateSizeWithCompletionBlock:. This method provides a way to asynchronously calculate the size of the disk cache, reporting both the number of files and the total file size. This is useful when querying large disk caches because the file system enumeration operation can take some time. --- SDWebImage/SDImageCache.h | 5 +++++ SDWebImage/SDImageCache.m | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/SDWebImage/SDImageCache.h b/SDWebImage/SDImageCache.h index d3699b60..afe07f47 100644 --- a/SDWebImage/SDImageCache.h +++ b/SDWebImage/SDImageCache.h @@ -154,4 +154,9 @@ typedef enum SDImageCacheType SDImageCacheType; */ - (int)getDiskCount; +/** + * Asynchronously calculate the disk cache's size. + */ +- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, unsigned long long totalSize))completionBlock; + @end diff --git a/SDWebImage/SDImageCache.m b/SDWebImage/SDImageCache.m index 22e37148..5fe3aae8 100644 --- a/SDWebImage/SDImageCache.m +++ b/SDWebImage/SDImageCache.m @@ -423,4 +423,37 @@ static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week return count; } +- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, unsigned long long totalSize))completionBlock +{ + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + + dispatch_async(self.ioQueue, ^ + { + NSUInteger fileCount = 0; + unsigned long long totalSize = 0; + + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSDirectoryEnumerator *fileEnumerator = [fileManager enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:@[ NSFileSize ] + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + + for (NSURL *fileURL in fileEnumerator) + { + NSNumber *fileSize; + [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; + totalSize += [fileSize unsignedLongLongValue]; + fileCount += 1; + } + + if (completionBlock) + { + dispatch_async(dispatch_get_main_queue(), ^ + { + completionBlock(fileCount, totalSize); + }); + } + }); +} + @end