SDWebImage 是 iOS 上最常見的圖片異步載入與快取方案。以下記錄手動導入的步驟,以及在 UITableView 中搭配快取策略使用的寫法。
1、把下載好的 SDWebImage 原始碼包加入工程。
2、進入 Build Phases,將原始碼包中的所有 .m 檔加入編譯。
3、匯入它依賴的兩個系統框架:MapKit.framework 與 ImageIO.framework。
4、加入主標頭檔 UIImageView+WebCache.h。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID = @"Beyond";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
// 池中沒取到,重新建立一個
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
}
// 設定該列獨有的內容
Status *s = _statuses[indexPath.row];
cell.textLabel.text = s.text;
cell.detailTextLabel.text = s.user.screenName;
cell.textLabel.numberOfLines = 0;
// 使用 SDWebImage 載入頭像,並指定快取策略
[cell.imageView setImageWithURL:[NSURL URLWithString:s.user.profileImageUrl]
placeholderImage:[UIImage imageNamed:@"avatar_default.png"]
options:SDWebImageLowPriority | SDWebImageRefreshCached | SDWebImageRetryFailed];
return cell;
}
SDWebImageRetryFailed:失敗後仍會再嘗試請求。預設情況下載入失敗的 URL 會被標記,不再重試;加上這個選項可以讓它在下次滾動到該列時重新嘗試,適合網路不穩的情境。
SDWebImageRefreshCached:即使已有磁碟快取,仍先向網路確認是否有更新版本。對於頭像這類會變動的資源很實用,代價是多一次請求。
SDWebImageLowPriority:降低該次下載的優先權,通常在 ScrollView 滾動時生效,讓當前可見內容的圖片優先載入,滾動過程明顯更順。
完整呼叫形式:
[cell.imageView setImageWithURL:[NSURL URLWithString:s.user.profileImageUrl] placeholderImage:[UIImage imageNamed:@"avatar_default.png"] options:SDWebImageLowPriority | SDWebImageRefreshCached | SDWebImageRetryFailed];
實務上,這三個選項可以依場景自由組合。若列表圖片基本不變,去掉 RefreshCached 能省下不少流量;若是即時性高的內容,則建議保留。另外記得設定 placeholderImage,讓網路延遲期間畫面不至于空白。