iOS利用SDWebImage圖片下載緩存

gcd8 11年前發布 | 165K 次閱讀 iOS開發 移動開發 SDWebImage

SDWebImage托管在github上。https://github.com/rs/SDWebImage

這個類庫提供一個UIImageView類別以支持加載來自網絡的遠程圖片。具有緩存管理、異步下載、同一個URL下載次數控制和優化等特征。
使用示范的代碼:

UITableView使用UIImageView+WebCache類(基本應用,UIImageView的一個category)

前提#import導入UIImageView+WebCache.h文件,然后在tableview的cellForRowAtIndexPath:方法下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
   if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
    }
// Here we use the new provided setImageWithURL: method to load the web image
   [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
   cell.textLabel.text = @"My Text";
   return cell;
}
基本代碼:[imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/image.jpg"]]; 

使用SDWebImageManager類:可以進行一些異步加載的工作。

SDWebImageManager *manager = [SDWebImageManager sharedManager];
UIImage *cachedImage = [manager imageWithURL:url]; // 將需要緩存的圖片加載進來
if (cachedImage) {
      // 如果Cache命中,則直接利用緩存的圖片進行有關操作
      // Use the cached image immediatly
} else {
      // 如果Cache沒有命中,則去下載指定網絡位置的圖片,并且給出一個委托方法
      // Start an async download
     [manager downloadWithURL:url delegate:self];
}

當然你的類要實現SDWebImageManagerDelegate協議,并且要實現協議的webImageManager:didFinishWithImage:方法。
// 當下載完成后,調用回調方法,使下載的圖片顯示

  • (void)webImageManager:(SDWebImageManager )imageManager didFinishWithImage:(UIImage )image { // Do something with the downloaded image }</pre>
    獨立的異步圖像下載 可能會單獨用到異步圖片下載,則一定要用downloaderWithURL:delegate:來建立一個SDWebImageDownloader實例。
    downloader = [SDWebImageDownloader downloaderWithURL:url delegate:self];
    這樣SDWebImageDownloaderDelegate協議的方法imageDownloader:didFinishWithImage:被調用時下載會立即開始并完成。
    獨立的異步圖像緩存
    SDImageCache類提供一個創建空緩存的實例,并用方法imageForKey:來尋找當前緩存。
    UIImage *myCachedImage = [[SDImageCache sharedImageCache] imageFromKey:myCacheKey];
    存儲一個圖像到緩存是使用方法storeImage: forKey:
    [[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
    默認情況下,圖像將被存儲在內存緩存和磁盤緩存中。如果僅僅是想內存緩存中,要使用storeImage:forKey:toDisk:方法的第三個參數帶一負值
    來替代。

 本文由用戶 gcd8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!