+ (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也就是在下載的時候優先會去獨本地緩存,下載成功之后會默認保存到本地緩存->如果是歷史下載請求且本地存在文件則直接全部數據立刻全部返回,否則按下載進度依次返回->觸發下載結束代理->查詢代理緩存數組執行與下載相關的代理內描述的操作