该类库所提供的功能
1、带有管理网络图片下载和缓存的UIImageView类别;
2、支持异步下载;
3、支持异步内存+磁盘缓存,自动清理过期缓存;
4、支持Gif;
5、支持WebP;
6、支持图片后台解压;
7、确保同样的URL不会下载多次;
8、伪造的URL不会尝试重新下载;
9、确保主线程不会堵塞;
10、高性能;
11、使用GCD和ARC;
12、支持64位;
目录结构
1、Downloader:图片下载相关类
2、Cache:图片缓存处理相关类
3、Utils:SDWebImageManager管理SDWebImageDownloader和SDImageCache;SDWebImageDecoder用来解压图片; SDWebImagePrefetcher预加载图片;
4、Categories:控件类目扩展
SDImageCache类结构
SDImageCache:主要提供三种缓存方式( SDImageCacheTypeNone、SDImageCacheTypeDisk、SDImageCacheTypeMemory),其中图片的磁盘缓存写操作采用异步处理方式。一般情况下,磁盘缓存的操作都采用异步处理。下面是 文件#import “SDImageCache.m”
中类实现的结构:
缓存图片包括4个方法:
- (void)storeImage:(UIImage *)image forKey:(NSString *)key;
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;
- (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key;
从缓存中获取图片包括3个方法(第一个方法异步获取):
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
根据键值从缓存中清除图片包括4个方法(全部方法都是异步操作):
- (void)removeImageForKey:(NSString *)key;
- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion;
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion;
清理缓存包括5个方法:
- (void)clearMemory;
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion;
- (void)clearDisk;
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock;
- (void)cleanDisk;
根据键值判断图片是否存在磁盘中(第一个方法异步获取):
- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;
- (BOOL)diskImageExistsWithKey:(NSString *)key;
其它方法,计算磁盘缓存大小、缓存中图片数、缓存中是否存在键值对应的图片等。
代码注释
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDImageCache.h"
#import "SDWebImageDecoder.h"
#import "UIImage+MultiFormat.h"
#import
// See https://github.com/rs/SDWebImage/pull/1141 for discussion
#pragma mark -----内存缓存类:添加观察者,内存警告时,清空内存缓存-----
@interface AutoPurgeCache : NSCache
@end
@implementation AutoPurgeCache
- (id)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
@end
// 缓存生命期1周:1 week
static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7;
// PNG signature bytes and data (below)
static unsigned char kPNGSignatureBytes[8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
// PNG签名的数据:装载kPNGSignatureBytes
static NSData *kPNGSignatureData = nil;
BOOL ImageDataHasPNGPreffix(NSData *data);
/**
* ImageData是否含有PNG前缀
*
* @param data 图片数据
*
* @return 图片是否含有PNG前缀
*/
BOOL ImageDataHasPNGPreffix(NSData *data) {
NSUInteger pngSignatureLength = [kPNGSignatureData length];
if ([data length] >= pngSignatureLength) {
if ([[data subdataWithRange:NSMakeRange(0, pngSignatureLength)] isEqualToData:kPNGSignatureData]) {
return YES;
}
}
return NO;
}
/**
* 计算图片所占内存大小
*
* @param image <#image description#>
*
* @return <#return value description#>
*/
FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
// 计算图片所消耗的内存注意乘以屏幕的比例因子
return image.size.height * image.size.width * image.scale * image.scale;
}
#pragma mark -----图片缓存类-----
@interface SDImageCache ()
// 内存缓存
@property (strong, nonatomic) NSCache *memCache;
// 磁盘缓存路径
@property (strong, nonatomic) NSString *diskCachePath;
// 保存缓存路径的数组
@property (strong, nonatomic) NSMutableArray *customPaths;
// 执行处理输入输出的等待队列
@property (SDDispatchQueueSetterSementics, nonatomic) dispatch_queue_t ioQueue;
@end
@implementation SDImageCache {
NSFileManager *_fileManager;
}
#pragma mark -- 单例
+ (SDImageCache *)sharedImageCache {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
#pragma mark -- 初始化
- (id)init {
// 默认命名空间default,也可以自定义命名空间
return [self initWithNamespace:@"default"];
}
- (id)initWithNamespace:(NSString *)ns {
// path = "/var/mobile/Containers/Data/Application/382D0176-0BC4-44E3-98FF-095D02B85D38/Library/Caches/default"
NSString *path = [self makeDiskCachePath:ns];
return [self initWithNamespace:ns diskCacheDirectory:path];
}
- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory {
if ((self = [super init])) {
// com.hackemist.SDWebImageCache.default
NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
// 初始化PNG签名数据initialise PNG signature data
kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8];
// 初始化执行处理输入输出的等待队列:Create IO serial queue
_ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
// 初始化缓存生命期: Init default values
_maxCacheAge = kDefaultCacheMaxCacheAge;
// 初始化内存缓存:Init the memory cache
_memCache = [[AutoPurgeCache alloc] init];
_memCache.name = fullNamespace;
// 初始化硬盘缓存:Init the disk cache
if (directory != nil) {
// /var/mobile/Containers/Data/Application/3EC2CFBB-6B30-4E4C-8CFE-11B717DEC9BE/Library/Caches/default/com.hackemist.SDWebImageCache.default
_diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
} else {
NSString *path = [self makeDiskCachePath:ns];
_diskCachePath = path;
}
// 是否解压图片:Set decompression to YES
_shouldDecompressImages = YES;
// 是否开启内存缓存:memory cache enabled
_shouldCacheImagesInMemory = YES;
// 设置默认不使用iCloud:Disable iCloud
_shouldDisableiCloud = YES;
dispatch_sync(_ioQueue, ^{
_fileManager = [NSFileManager new];
});
#if TARGET_OS_IOS
// Subscribe to app events
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearMemory)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(cleanDisk)
name:UIApplicationWillTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(backgroundCleanDisk)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
#endif
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
SDDispatchQueueRelease(_ioQueue);
}
#pragma mark -- 图片路径操作
/**
* 往数组中添加唯一缓存路径
*
* @param path 路径
*/
- (void)addReadOnlyCachePath:(NSString *)path {
if (!self.customPaths) {
self.customPaths = [NSMutableArray new];
}
if (![self.customPaths containsObject:path]) {
[self.customPaths addObject:path];
}
}
/**
* 返回缓存完整路径,其中文件名是根据key值生成的MD5值
*
* @param key key
* @param path 路径
*
* @return <#return value description#>
*/
- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path {
NSString *filename = [self cachedFileNameForKey:key];// 508746268d43f962e80def6392aff711.35786508303135633
return [path stringByAppendingPathComponent:filename];// /var/mobile/Containers/Data/Application/111DBEDD-3D5E-457D-867F-EC0E08260A46/Library/Caches/default/com.hackemist.SDWebImageCache.default/508746268d43f962e80def6392aff711.35786508303135633
}
- (NSString *)defaultCachePathForKey:(NSString *)key {
return [self cachePathForKey:key inPath:self.diskCachePath];
}
#pragma mark SDImageCache (private)
/**
* 根据key值生成文件名:采用MD5
*
* @param key key
*
* @return 文件名
*/
- (NSString *)cachedFileNameForKey:(NSString *)key {
const char *str = [key UTF8String];
if (str == NULL) {
str = "";
}
unsigned char r[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, (CC_LONG)strlen(str), r);
NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
r[11], r[12], r[13], r[14], r[15], [[key pathExtension] isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", [key pathExtension]]];
return filename;
}
#pragma mark ImageCache
#pragma mark -- 初始化磁盘缓存路径
/**
* 初始化磁盘缓存路径
*
* @param fullNamespace 磁盘缓存命名空间:默认为default
*
* @return 磁盘缓存路径
*/
-(NSString *)makeDiskCachePath:(NSString*)fullNamespace{
// /var/mobile/Containers/Data/Application/382D0176-0BC4-44E3-98FF-095D02B85D38/Library/Caches
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
return [paths[0] stringByAppendingPathComponent:fullNamespace];
}
#pragma mark -- 缓存图片
/**
* 缓存图片
*
* @param image 图片
* @param recalculate 是否重新计算
* @param imageData imageData
* @param key 缓存的key
* @param toDisk 是否缓存到磁盘
*/
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk {
if (!image || !key) {
return;
}
// 缓存到内存
if (self.shouldCacheImagesInMemory) {
NSUInteger cost = SDCacheCostForImage(image);
[self.memCache setObject:image forKey:key cost:cost];
}
// 缓存到磁盘,采用异步操作
if (toDisk) {
dispatch_async(self.ioQueue, ^{
NSData *data = imageData;
if (image && (recalculate || !data)) {
#if TARGET_OS_IPHONE
// We need to determine if the image is a PNG or a JPEG
// PNGs are easier to detect because they have a unique signature (http://www.w3.org/TR/PNG-Structure.html)
// The first eight bytes of a PNG file always contain the following (decimal) values:
// 137 80 78 71 13 10 26 10
// PNG图片有统一的签名较易甄别,前8个字节通常包含:137 80 78 71 13 10 26 10
// If the imageData is nil (i.e. if trying to save a UIImage directly or the image was transformed on download)
// and the image has an alpha channel, we will consider it PNG to avoid losing the transparency
// 如图片的imageData为空(如果试图直接保存一个UIImage 或者 图片是由下载转换得来),且图片含有alpha通道,将进行PNG缓存处理避免失去透明度
int alphaInfo = CGImageGetAlphaInfo(image.CGImage);
BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone ||
alphaInfo == kCGImageAlphaNoneSkipFirst ||
alphaInfo == kCGImageAlphaNoneSkipLast);
BOOL imageIsPng = hasAlpha;
// But if we have an image data, we will look at the preffix
if ([imageData length] >= [kPNGSignatureData length]) {
imageIsPng = ImageDataHasPNGPreffix(imageData);
}
if (imageIsPng) {
data = UIImagePNGRepresentation(image);
}
else {
data = UIImageJPEGRepresentation(image, (CGFloat)1.0);
}
#else
data = [NSBitmapImageRep representationOfImageRepsInArray:image.representations usingType: NSJPEGFileType properties:nil];
#endif
}
[self storeImageDataToDisk:data forKey:key];
});
}
}
- (void)storeImage:(UIImage *)image forKey:(NSString *)key {
[self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:YES];
}
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk {
[self storeImage:image recalculateFromImage:YES imageData:nil forKey:key toDisk:toDisk];
}
/**
* 保存图片imageData到磁盘
*
* @param imageData imageData
* @param key 缓存的key
*/
- (void)storeImageDataToDisk:(NSData *)imageData forKey:(NSString *)key {
if (!imageData) {
return;
}
// 如果不存在该路径,则创建
if (![_fileManager fileExistsAtPath:_diskCachePath]) {
[_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
}
// 根据key获取缓存路径:get cache Path for image key
// /var/mobile/Containers/Data/Application/752F97A5-F9EB-4C6C-A96B-2C785087B4A6/Library/Caches/default/com.hackemist.SDWebImageCache.default/fcc1e50837ec9a5d0cca14cda3339ca7.webp
NSString *cachePathForKey = [self defaultCachePathForKey:key];
// 将缓存路径转换为URL:transform to NSUrl
// file:///var/mobile/Containers/Data/Application/752F97A5-F9EB-4C6C-A96B-2C785087B4A6/Library/Caches/default/com.hackemist.SDWebImageCache.default/fcc1e50837ec9a5d0cca14cda3339ca7.webp
NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
// 保存数据
[_fileManager createFileAtPath:cachePathForKey contents:imageData attributes:nil];
// 关闭iCloud备份:disable iCloud backup
if (self.shouldDisableiCloud) {
[fileURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:nil];
}
}
#pragma mark -- 磁盘中是否存在图片
/**
* 根据key判断是否Image是否存在磁盘中
*
* @param key key
*
* @return <#return value description#>
*/
- (BOOL)diskImageExistsWithKey:(NSString *)key {
BOOL exists = NO;
// this is an exception to access the filemanager on another queue than ioQueue, but we are using the shared instance
// from apple docs on NSFileManager: The methods of the shared NSFileManager object can be called from multiple threads safely.
exists = [[NSFileManager defaultManager] fileExistsAtPath:[self defaultCachePathForKey:key]];
// fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
// 去掉路径的扩展名后在进行检查:checking the key with and without the extension
if (!exists) {
exists = [[NSFileManager defaultManager] fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
}
return exists;
}
/**
* 根据key判断是否Image是否存在磁盘中:异步处理
*
* @param key key
* @param completionBlock Image是否存在磁盘中回调
*/
- (void)diskImageExistsWithKey:(NSString *)key completion:(SDWebImageCheckCacheCompletionBlock)completionBlock {
dispatch_async(_ioQueue, ^{
BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];
// fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
// checking the key with and without the extension
if (!exists) {
exists = [_fileManager fileExistsAtPath:[[self defaultCachePathForKey:key] stringByDeletingPathExtension]];
}
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(exists);
});
}
});
}
#pragma mark -- 根据key从磁盘或内存中获取图片
/**
* 根据key从内存中获取图片
*
* @param key key
*
* @return <#return value description#>
*/
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key {
return [self.memCache objectForKey:key];
}
/**
* 根据key从磁盘缓存中获取图片
*
* @param key key
*
* @return <#return value description#>
*/
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key {
// 首先查看内存的缓存中是否含有该key所对应的图片,在检查磁盘缓存
// First check the in-memory cache...
UIImage *image = [self imageFromMemoryCacheForKey:key];
if (image) {
return image;
}
// Second check the disk cache...
UIImage *diskImage = [self diskImageForKey:key];
if (diskImage && self.shouldCacheImagesInMemory) {
// 将图片写入内存缓存
NSUInteger cost = SDCacheCostForImage(diskImage);
[self.memCache setObject:diskImage forKey:key cost:cost];
}
return diskImage;
}
/**
* 根据key在磁盘缓存中搜索图片
*
* @param key key
*
* @return 图片数据
*/
- (NSData *)diskImageDataBySearchingAllPathsForKey:(NSString *)key {
NSString *defaultPath = [self defaultCachePathForKey:key];
NSData *data = [NSData dataWithContentsOfFile:defaultPath];
if (data) {
return data;
}
// fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
// checking the key with and without the extension
data = [NSData dataWithContentsOfFile:[defaultPath stringByDeletingPathExtension]];
if (data) {
return data;
}
NSArray *customPaths = [self.customPaths copy];
for (NSString *path in customPaths) {
NSString *filePath = [self cachePathForKey:key inPath:path];
NSData *imageData = [NSData dataWithContentsOfFile:filePath];
if (imageData) {
return imageData;
}
// fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
// checking the key with and without the extension
imageData = [NSData dataWithContentsOfFile:[filePath stringByDeletingPathExtension]];
if (imageData) {
return imageData;
}
}
return nil;
}
- (UIImage *)diskImageForKey:(NSString *)key {
NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
if (data) {
UIImage *image = [UIImage sd_imageWithData:data];
// 根据图片的scale 或 图片中的图片组 重新计算返回图片
image = [self scaledImageForKey:key image:image];
if (self.shouldDecompressImages) {
image = [UIImage decodedImageWithImage:image];
}
return image;
}
else {
return nil;
}
}
- (UIImage *)scaledImageForKey:(NSString *)key image:(UIImage *)image {
return SDScaledImageForKey(key, image);
}
/**
* 根据key从磁盘缓存中获取图片:异步操作
*
* @param key key
* @param doneBlock 根据key从磁盘缓存中获取图片回调
*
* @return <#return value description#>
*/
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
if (!doneBlock) {
return nil;
}
if (!key) {
doneBlock(nil, SDImageCacheTypeNone);
return nil;
}
// First check the in-memory cache...
UIImage *image = [self imageFromMemoryCacheForKey:key];
if (image) {
doneBlock(image, SDImageCacheTypeMemory);
return nil;
}
NSOperation *operation = [NSOperation new];
dispatch_async(self.ioQueue, ^{
if (operation.isCancelled) {
return;
}
// 这里使用自动释放池,自己的理解:里面的操作内存消耗过大,需要在系统回收的时候,优先、及时回收自动释放池中分配的对象,优化内存使用。
@autoreleasepool {
UIImage *diskImage = [self diskImageForKey:key];
if (diskImage && self.shouldCacheImagesInMemory) {
// 将图片写入内存缓存
NSUInteger cost = SDCacheCostForImage(diskImage);
[self.memCache setObject:diskImage forKey:key cost:cost];
}
dispatch_async(dispatch_get_main_queue(), ^{
doneBlock(diskImage, SDImageCacheTypeDisk);
});
}
});
return operation;
}
#pragma mark -- 根据key从缓存中清除图片
- (void)removeImageForKey:(NSString *)key {
[self removeImageForKey:key withCompletion:nil];
}
- (void)removeImageForKey:(NSString *)key withCompletion:(SDWebImageNoParamsBlock)completion {
[self removeImageForKey:key fromDisk:YES withCompletion:completion];
}
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk {
[self removeImageForKey:key fromDisk:fromDisk withCompletion:nil];
}
/**
* 根据key从缓存中清除图片
*
* @param key key
* @param fromDisk 是否磁盘缓存
* @param completion 缓存图片清除回调
*/
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(SDWebImageNoParamsBlock)completion {
if (key == nil) {
return;
}
// 内存缓存清除
if (self.shouldCacheImagesInMemory) {
[self.memCache removeObjectForKey:key];
}
// 磁盘缓存清除
if (fromDisk) {
dispatch_async(self.ioQueue, ^{
[_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
});
} else if (completion){
completion();
}
}
#pragma mark -- 设置
- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
self.memCache.totalCostLimit = maxMemoryCost;
}
- (NSUInteger)maxMemoryCost {
return self.memCache.totalCostLimit;
}
- (NSUInteger)maxMemoryCountLimit {
return self.memCache.countLimit;
}
- (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit {
self.memCache.countLimit = maxCountLimit;
}
#pragma mark -- 清空 或清除 缓存
/**
* 清空内存缓存
*/
- (void)clearMemory {
[self.memCache removeAllObjects];
}
/**
* 清空磁盘缓存
*/
- (void)clearDisk {
[self clearDiskOnCompletion:nil];
}
/**
* 清空磁盘缓存
*
* @param completion 磁盘缓存清空回调
*/
- (void)clearDiskOnCompletion:(SDWebImageNoParamsBlock)completion
{
dispatch_async(self.ioQueue, ^{
[_fileManager removeItemAtPath:self.diskCachePath error:nil];
[_fileManager createDirectoryAtPath:self.diskCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion();
});
}
});
}
/**
* 清除磁盘缓存
*/
- (void)cleanDisk {
[self cleanDiskWithCompletionBlock:nil];
}
/**
* 清除磁盘缓存,异步操作:1、清除过期的缓存文件;2、缓存超过设定阈值时,按时间顺序删除缓存中的图片,直到缓存剩余空间达阈值的一半
*
* @param completion 磁盘缓存清除回调
*/
- (void)cleanDiskWithCompletionBlock:(SDWebImageNoParamsBlock)completionBlock {
dispatch_async(self.ioQueue, ^{
// dickCacheURL:file:///var/mobile/Containers/Data/Application/E42DF859-9AF1-46B3-B518-FB62ECE73D33/Library/Caches/default/com.hackemist.SDWebImageCache.default/
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
// resourceKeys包含要了解的属性:允许判断遍历到的URL所指对象是否是目录、允许判断遍历返回的URL所指项目的最后修改时间、URL目录中所分配的空间大小
NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];
// 使用目录枚举器获取缓存文件:This enumerator prefetches useful properties for our cache files.
// 使用NSdirectoryEnumerator遍历所有的缓存文件,获取文件属性,如我们需要的文件大小信息,是不会有性能问题的。NSdirectoryEnumerator获取文件属性是通过查看文件的inode数据,并不需要想象中的fileopen和fileclose。
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:resourceKeys
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
// 计算过期时间,默认1周以前的缓存文件为过期
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge];
NSMutableDictionary *cacheFiles = [NSMutableDictionary dictionary]; // 当前保存下来文件的fileURL
NSUInteger currentCacheSize = 0; // 当前保存下来文件的总内存大小
// Enumerate all of the files in the cache directory. This loop has two purposes:
//
// 1. Removing files that are older than the expiration date.
// 2. Storing file attributes for the size-based cleanup pass.
// 遍历目录枚举器:1、清除过期的文件;2、
NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init]; // 将会删除的文件fileURL数组
for (NSURL *fileURL in fileEnumerator) {
NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL];
// 跳过目录:Skip directories.
if ([resourceValues[NSURLIsDirectoryKey] boolValue]) {
continue;
}
// 记录超过过期日期文件的fileURL:Remove files that are older than the expiration date;
NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
[urlsToDelete addObject:fileURL];
continue;
}
// 保存保留下来的文件的引用并计算文件总的大小:Store a reference to this file and account for its total size.
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize += [totalAllocatedSize unsignedIntegerValue];
[cacheFiles setObject:resourceValues forKey:fileURL];
}
// 删除缓存中过期的文件
for (NSURL *fileURL in urlsToDelete) {
[_fileManager removeItemAtURL:fileURL error:nil];
}
// If our remaining disk cache exceeds a configured maximum size, perform a second
// size-based cleanup pass. We delete the oldest files first.
// 当设置的maxCacheSize > 0 且 当前缓存中的文件所占内存大于设置的最大缓存时,按时间顺序删除文件,直到缓存剩余空间达阈值的一半
if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize) {
// 清除缓存目标是最大缓存的一半:Target half of our maximum cache size for this cleanup pass.
const NSUInteger desiredCacheSize = self.maxCacheSize / 2;
// 缓存文件排序,最老的文件先清除:Sort the remaining cache files by their last modification time (oldest first).
NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
usingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
}];
// Delete files until we fall below our desired cache size.
for (NSURL *fileURL in sortedFiles) {
if ([_fileManager removeItemAtURL:fileURL error:nil]) {
NSDictionary *resourceValues = cacheFiles[fileURL];
NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
currentCacheSize -= [totalAllocatedSize unsignedIntegerValue];
if (currentCacheSize < desiredCacheSize) {
break;
}
}
}
}
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock();
});
}
});
}
/**
* 后台清理磁盘缓存:收到UIApplicationDidEnterBackgroundNotification时,在手机系统后台进行如上面描述的异步磁盘缓存清理
*/
- (void)backgroundCleanDisk {
Class UIApplicationClass = NSClassFromString(@"UIApplication");
if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
return;
}
// 使用sharedApplication开启后台任务cleanDiskWithCompletionBlock:
UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// 清理任何未完成的任务作业,标记完全停止或结束任务:Clean up any unfinished task business by marking where you stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// 开始长时间后台运行的任务并且立即return:Start the long-running task and return immediately.
[self cleanDiskWithCompletionBlock:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
#pragma mark -- 计算缓存大小、缓存中图片数
/**
* 同步操作:获取缓存中所有文件的大小
*
* @return <#return value description#>
*/
- (NSUInteger)getSize {
__block NSUInteger size = 0;
// 需要同步操作:等待队列self.ioQueue中的任务执行完后(有可能队列中的任务正在添加图片或者删除图片操作),再进行获取文件大小计算
dispatch_sync(self.ioQueue, ^{
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
for (NSString *fileName in fileEnumerator) {
NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
size += [attrs fileSize];
}
});
return size;
}
/**
* 同步操作:获取磁盘缓存中图片数
*
* @return <#return value description#>
*/
- (NSUInteger)getDiskCount {
__block NSUInteger count = 0;
dispatch_sync(self.ioQueue, ^{
NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
count = [[fileEnumerator allObjects] count];
});
return count;
}
/**
* 异步操作:获取缓存中图片数及图片所占内存总大小
*
* @param completionBlock <#completionBlock description#>
*/
- (void)calculateSizeWithCompletionBlock:(SDWebImageCalculateSizeBlock)completionBlock {
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
dispatch_async(self.ioQueue, ^{
NSUInteger fileCount = 0;
NSUInteger totalSize = 0;
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 unsignedIntegerValue];
fileCount += 1;
}
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(fileCount, totalSize);
});
}
});
}
@end