您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 圖片異步下載與緩存:從零打造 SDWebImage 式管理器

編輯:iOS 相關教學

寫在前面

在 iOS 開發中,無論是 UITableView 還是 UICollectionView,從網路抓圖片塞進 cell 都是極常見的需求。市面上已經有不少成熟的三方庫把下載與緩存都封裝好了,但從學習的角度出發,讀懂源碼、理解原理,再依自身需求寫一份自己的實作,是很值得的投資。本文就把整個實作的思路整理出來。

基本思路

• 在 cell 中放一個 UIImageView

• cell 持有 url,發起下載請求並註冊完成通知,在通知回呼中取出圖片並設定

• 下載管理類負責開啟下載執行緒與多層緩存(記憶體 + 檔案),完成後送出通知

• 為避免 cell 重用與異步下載造成圖片錯位,cell 在發起下載前先設好預設圖,同時為 imageView 設定 tag 標記目前對應的 url

整體框架

關鍵程式碼

cell 初始化,並註冊下載完成通知

 @interface SQPhotoCell () @property (strong, nonatomic) UIImageView *photoView; //Tag 指向當前可見圖片的 url,可過濾掉已經滑出螢幕的圖片 @property (strong, nonatomic) NSString *imageViewTag; @end -(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _photoView = [[UIImageView alloc] initWithFrame:CGRectZero]; _photoView.userInteractionEnabled = YES; [self.contentView addSubview:_photoView]; _imageViewTag = @""; //註冊下載完成通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadCallback:) name:NOTIFICATION_DOWNLOAD_CALLBACK object:nil]; } return self; }

cell 的通知處理

 //通知處理事件 - (void)downloadCallback:(NSNotification *)noti { NSDictionary *notiDic = noti.userInfo; NSString *urlStr = [notiDic objectForKey:@"urlStr"]; UIImage *image = [notiDic objectForKey:@"image"]; if ([self.imageViewTag isEqualToString:urlStr]) { self.photoView.image = image; } }

cell 發起下載請求

 - (void)setImageWithURL:(NSString *)urlStr placeholder:(UIImage *)placeholder { self.imageViewTag = urlStr; //先設預設圖,用來清掉重用前可能殘留的圖片 self.photoView.image = placeholder; if (urlStr) { SQWebImageManager *manager = [SQWebImageManager sharedManager]; [manager downloadImageWithURLString:urlStr]; } [self setNeedsDisplay]; }

下載管理類的下載方法

 - (void)downloadImageWithURLString:(NSString *)urlStr { // 1.先查記憶體緩存 {urlStr: image} UIImage *cacheImage = [self.imageCache objectForKey:urlStr]; if (cacheImage != nil) { //送出下載完成通知,帶回 urlStr 與圖片 [self postDownloadCompleteNotification:urlStr withImage:cacheImage]; return; } // 2.再查沙盒緩存 NSString *cacheImagePath = [self cacheImagePathWithURLString:urlStr]; cacheImage = [UIImage imageWithContentsOfFile:cacheImagePath]; if (cacheImage != nil) { //從沙盒讀到了圖片,順手寫回記憶體緩存,下次直接命中 [self.imageCache setObject:cacheImage forKey:urlStr]; // 回傳圖片 [self postDownloadCompleteNotification:urlStr withImage:cacheImage]; return; } // 3.再查操作緩存,避免同一張圖被重複下載 {urlStr: operation} if (self.operationCache[urlStr] != nil) { // 已經有操作在下載這張圖了 NSLog(@"有操作正在下載這張圖片"); return; } // 1.建立下載圖片的操作 SQDownloadOperation *downloadOperation = [SQDownloadOperation downloadOperationWithURLString:urlStr cacheImagePath:cacheImagePath]; // 設定操作完成後的回呼,在 downloadOperation 的 main 方法結束時觸發 __weak typeof(downloadOperation) weakDownloadOperation = downloadOperation; downloadOperation.completionBlock = ^() { // 1.取得下載完成的圖像 UIImage *image = [weakDownloadOperation getDownloadImage]; // 2.從操作緩存中移除該操作 [self.operationCache removeObjectForKey:urlStr]; // 3.判斷圖像是否為空(縮圖) if (image != nil) { // 寫入圖片記憶體緩存 [self.imageCache setObject:image forKey:urlStr]; // 4.回主線程回呼 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //送出下載完成通知 [self postDownloadCompleteNotification:urlStr withImage:image]; }]; } else { //如果圖片為空,改用下載失敗時的預設圖 image = [UIImage imageNamed:@"default.jpg"]; // 4.回主線程回呼 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //送出下載完成通知 [self postDownloadCompleteNotification:urlStr withImage:image]; }]; } }; // 2.把下載操作加入佇列 [self.downloadQueue addOperation:downloadOperation]; // 3.把下載操作加入操作緩存 [self.operationCache setObject:downloadOperation forKey:urlStr]; } - (void)postDownloadCompleteNotification:(NSString *)urlStr withImage:(UIImage *)image { NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:urlStr, @"urlStr", image, @"image",nil]; [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_DOWNLOAD_CALLBACK object:nil userInfo:dic]; }

控制器中的使用

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { SQPhotoCell *cell = (SQPhotoCell *)[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; UIImage *placeholder = [UIImage imageNamed:@"gray.jpg"]; NSString *imageUrl = @"https://www.taopic.comhttps://img.warting.com/allimg/110925/9117-11092509545328.jpg"; [cell setImageWithURL:imageUrl placeholder:placeholder]; return cell; }

寫在後面

這套思路是參考 SDWebImage 的架構:三層快取(記憶體 → 沙盒 → 網路)加上操作緩存去重。雖然原始碼就在眼前,也有不少文章解析,但在還不太熟悉多執行緒編程的時候上手,還是花了不少時間。前期一直急著想赶快做出來,很多東西都是懵懵懂懂就往下寫,後來才慢慢意識到:其實慢就是快。慢下來把問題想清楚再動手,前期感覺好像沒進度,越到後面越能體會這種慢的好處。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved