1. 程式人生 > >IOS網路圖片快取之SDWebImage

IOS網路圖片快取之SDWebImage

載入網路圖片可以說是網路應用中必備的。如果單純的去下載圖片,而不去做多執行緒、快取等技術去優化,載入圖片時的效果與使用者體驗就會很差。

處理網路圖片快取步驟:

1、根據圖片URL查詢記憶體是否有這張圖片,有則返回圖片,沒有則進入下一步。

2、查詢本地磁碟儲存是否有這張圖片,有則返回圖片,沒有進行下一步。

3、從網路上下載該圖片,下載完後儲存到記憶體和本地磁碟儲存上,並返回該圖片。


使用第三方框架SDWebImage

特點:

1、依賴庫很少,功能全面

2、自動實現磁碟快取

3、快取圖片名字是以MD5進行加密的字尾名進行命名

4、只需要一個方法就可以實現

多執行緒&帶緩衝等效果


使用SDWebImage 方法實現快取圖片功能

#pragma mark - 資料來源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.appList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *ID = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

	//用模型來填充每個cell
	XNApp *app = self.appList[indexPath.row];
	cell.textLabel.text = app.name;  //設定文字


	//使用SDWebImage來完成上面的功能. 針對ImageView.
	//一句話, 自動實現了非同步下載. 圖片本地快取. 網路下載. 自動設定佔位符.
	[cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"user_default"]];


	return cell;
}


SDWebImage中的一些引數 修改:

* SDWebImageRetryFailed = 1<< 0,    預設選項,失敗後重試 * SDWebImageLowPriority = 1<< 1,     使用低優先順序 * SDWebImageCacheMemoryOnly = 1<< 2,    僅僅使用記憶體快取 * SDWebImageProgressiveDownload = 1<< 3,   
顯示現在進度 * SDWebImageRefreshCached = 1<< 4,     重新整理快取 * SDWebImageContinueInBackground =1 << 5,    後臺繼續下載影象 * SDWebImageHandleCookies = 1<< 6,     處理 Cookie * SDWebImageAllowInvalidSSLCertificates= 1 << 7,     允許無效的 SSL 驗證 * SDWebImageHighPriority = 1<< 8,      高優先順序 * SDWebImageDelayPlaceholder = 1<< 9      延遲顯示佔位圖片