SDWebImage的基本用法及常見問題

weixin_33859844發表於2017-07-24

SDWebImage的基本用法

1.框架整合

  • CocoaPods整合 : pod 'SDWebImage'
  • 若要載入GIF圖 : pod 'SDWebImage/GIF'

2.準備工作

* 載入靜態圖匯入標頭檔案 `#import <UIImageView+WebCache.h>`
* 載入GIF圖匯入標頭檔案 `#import <FLAnimatedImageView+WebCache.h>`
* 進度指示器匯入標頭檔案 : `#import <UIView+WebCache.h>`
* 準備控制元件
    * 展示靜態圖 `@property (weak, nonatomic) IBOutlet UIImageView *imgView;`
    * 展示GIF/靜態圖 `@property (weak, nonatomic) IBOutlet FLAnimatedImageView *imgView;`

3.載入GIF圖

- (void)loadGIF {
    // 載入網路gif圖
    NSURL *URL = [NSURL URLWithString:@"http://image.nihaowang.com/news/2015-04-27/c30f866d-9300-4f6e-86f6-58f408630e14.gif"];

    [self.imgView sd_setImageWithURL:URL];
}

4.監聽圖片下載進度

- (void)loadProgress {

    NSURL *URL = [NSURL URLWithString:@"http://img.taopic.com/uploads/allimg/140806/235020-140P60H10661.jpg"];
---------------------------------------------------------------------------------
//用此方法下載,SDWebImage會自動檢查圖片是否已經快取,如已經快取則從快取位置讀取,否則從網路下載,讀取順序是: 記憶體快取->磁碟快取->網路載入
    //個人理解此方法意思為*載入圖片*
    [self.imgView sd_setImageWithURL:URL placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {

        // receivedSize : 接收的圖片大小;expectedSize : 圖片的總大小
        float progress = (float)receivedSize / expectedSize;
        NSLog(@"%f %@",progress,targetURL);

    } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        NSLog(@"圖片下載完成 %@",image);
    }];
}
---------------------------------------------------------------------------------
//用此方法下載,SDWebImage不會自動檢查圖片是否已經快取,每次執行重新下載圖片
    //個人理解此方法意思為*下載圖片*
    [[SDWebImageManager sharedManager].imageDownloader downloadImageWithURL:url options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        NSLog(@"下載的進度:%zd / %zd", receivedSize, expectedSize);
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        [data writeToFile:@"/Users/apple/Desktop/aaa.png" atomically:true];
        NSLog(@"%@", NSStringFromCGSize(image.size));
    }];

options所有列舉值:

    //失敗後重試
     SDWebImageRetryFailed = 1 << 0,
      
     //UI互動期間開始下載,導致延遲下載比如UIScrollView減速。
     SDWebImageLowPriority = 1 << 1,
      
     //只進行記憶體快取
     SDWebImageCacheMemoryOnly = 1 << 2,
      
     //這個標誌可以漸進式下載,顯示的影像是逐步在下載
     SDWebImageProgressiveDownload = 1 << 3,
      
     //重新整理快取
     SDWebImageRefreshCached = 1 << 4,
      
     //後臺下載
     SDWebImageContinueInBackground = 1 << 5,
      
     //NSMutableURLRequest.HTTPShouldHandleCookies = YES;
      
     SDWebImageHandleCookies = 1 << 6,
      
     //允許使用無效的SSL證書
     //SDWebImageAllowInvalidSSLCertificates = 1 << 7,
      
     //優先下載
     SDWebImageHighPriority = 1 << 8,
      
     //延遲佔位符
     SDWebImageDelayPlaceholder = 1 << 9,
      
     //改變動畫形象
     SDWebImageTransformAnimatedImage = 1 << 10,

5.進度指示器

  • 匯入標頭檔案 : #import <UIView+WebCache.h>
- (void)loadProgressIndicator {

    // http://img.taopic.com/uploads/allimg/140806/235017-140P60PG685.jpg
    NSURL *URL = [NSURL URLWithString:@"http://img.taopic.com/uploads/allimg/140126/235002-14012609350290.jpg"];

    // 展示進度指示器
    [self.imgView sd_setShowActivityIndicatorView:YES];
    [self.imgView sd_setIndicatorStyle:UIActivityIndicatorViewStyleGray];

    [self.imgView sd_setImageWithURL:URL];
}

6.Manager下載圖片

- (void)LoadImageWithManager {
    NSURL *URL = [NSURL URLWithString:@"http://pic37.nipic.com/20140209/8821914_163234218136_2.jpg"];

    [[SDWebImageManager sharedManager] loadImageWithURL:URL options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {

        // receivedSize : 接收的圖片大小;expectedSize : 圖片的總大小
        float progress = (float)receivedSize / expectedSize;
        NSLog(@"%f %@",progress,targetURL);

    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        // 圖片賦值
        self.imgView.image = image;
    }];
}

SD常見問題

1> 圖片檔案快取的時間有多長:1周

_maxCacheAge = kDefaultCacheMaxCacheAge

2> SDWebImage 的記憶體快取是用什麼實現的?

NSCache

3> SDWebImage 的最大併發數是多少?

maxConcurrentDownloads = 6

4> SDWebImage 支援動圖嗎?GIF

//SDWebImage4.0以後改用此方法,效能更加
#import <FLAnimatedImageView+WebCache.h>
[self.imageView sd_setImageWithURL:url];
------------------------------------------------------------
//SDWebImage4.0以前使用此方法
#import <ImageIO/ImageIO.h>
[UIImage animatedImageWithImages:images duration:duration];

5> SDWebImage是如何區分不同格式的影像的

  • 根據影像資料第一個位元組來判斷的!
    • PNG:0x89
    • JPG:0xFF
    • GIF:0x47


      6257530-35a53660da640654.png

6> SDWebImage 快取圖片的名稱是怎麼確定的!

  • md5
    • 如果單純使用 檔名儲存,重名的機率很高!
    • 使用 MD5 的雜湊函式!對完整的 URL 進行 md5,結果是一個 32 個字元長度的字串!

7> SDWebImage 的記憶體警告是如何處理的!

  • 利用通知中心觀察
  • - UIApplicationDidReceiveMemoryWarningNotification 接收到記憶體警告的通知
    • 執行 clearMemory 方法,清理記憶體快取!
  • - UIApplicationWillTerminateNotification 接收到應用程式將要終止通知
    • 執行 cleanDisk 方法,清理磁碟快取!
  • - UIApplicationDidEnterBackgroundNotification 接收到應用程式進入後臺通知
    • 執行 backgroundCleanDisk 方法,後臺清理磁碟!
    • 通過以上通知監聽,能夠保證快取檔案的大小始終在控制範圍之內!
    • clearDisk 清空磁碟快取,將所有快取目錄中的檔案,全部刪除!
      實際工作,將快取目錄直接刪除,再次建立一個同名空目錄!

相關文章