+ (NSURLCache *)defaultURLCache { ???// It‘s been discovered that a crash will occur on certain versions ???// of iOS if you customize the cache. ???// ???// More info can be found here: https://devforums.apple.com/message/1102182#1102182 ???// ???// When iOS 7 support is dropped, this should be modified to use ???// NSProcessInfo methods instead. ???if ([[[UIDevice currentDevice] systemVersion] compare:@"8.2" options:NSNumericSearch] == NSOrderedAscending) { ???????return [NSURLCache sharedURLCache]; ???} ???return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024 ????????????????????????????????????????diskCapacity:150 * 1024 * 1024 ????????????????????????????????????????????diskPath:@"com.alamofire.imagedownloader"];}+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration { ???NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; ???//TODO set the default HTTP headers ???configuration.HTTPShouldSetCookies = YES; ???configuration.HTTPShouldUsePipelining = NO; ???configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy; ???configuration.allowsCellularAccess = YES; ???configuration.timeoutIntervalForRequest = 60.0; ???configuration.URLCache = [AFImageDownloader defaultURLCache]; ???return configuration;}
磁盘缓存
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity { ???if (self = [super init]) { ???????self.memoryCapacity = memoryCapacity; ???????self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity; ???????self.cachedImages = [[NSMutableDictionary alloc] init]; ???????NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]]; ???????self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); ???????[[NSNotificationCenter defaultCenter] ????????addObserver:self ????????selector:@selector(removeAllImages) ????????name:UIApplicationDidReceiveMemoryWarningNotification ????????object:nil]; ???} ???return self;}
内存缓存
图片缓存策略(个人理解):
图片设置路径->从内存字典中查找缓存的image对象->调用网络请求->根据NSURLRequst的策略是否只读缓存->不是只读缓存则开启下载操作->如果该下载已经存在则不新建下载而是只把代理(保存了成功失败的操作和对象信息)打包到管理代理数组,不存在同时会新建下载请求->下载请求管理对象绑定了一个磁盘与内存缓存对象NNSURLCanche也就是在下载的时候优先会去独本地缓存,下载成功之后会默认保存到本地缓存->如果是历史下载请求且本地存在文件则直接全部数据立刻全部返回,否则按下载进度依次返回->触发下载结束代理->查询代理缓存数组执行与下载相关的代理内描述的操作
AFNetworking的缓存使用
原文地址:https://www.cnblogs.com/yuxiaoyiyou/p/9328109.html