SDWebImage的簡單使用


一、前言

  第一次使用SDWebImage是在自己做《康復醫生》的時候。記得那時有一個表格要顯示所有的用戶頭像。不使用它的時候每次加載該table都會很卡頓,后來使用后發現不卡頓了。瞬間感覺這個世界好有愛。

二、安裝

  首先,SDWebImage的git地址是:https://github.com/rs/SDWebImage。我們可以直接到這里進行下載,然后添加到自己的項目中去。

三、使用場景(前提是已經導入了SDWebImage這個庫)

1、場景一、加載圖片

    使用SDWebImage可以去加載遠程圖片,而且還會緩存圖片,下次請求會看一下是否已經存在於緩存中,如果是的話直接取本地緩存,如果不是的話則重新請求。使用方法很簡單,在需要使用該場景的類中導入

#import "UIImageView+WebCache.h"

然后調用:

- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;

即可。

  我們還可以在UIImageView+WebCache.h中看到其他的方法,和上邊的方法類似,讀者自行查看即可。

2、場景二、使用它做本地緩存

  很多時候我們可能拍照得到的一張圖片要多個地方使用,那么我們就希望可以把這張圖片放到緩存里面,然后每次用這張圖片的時候就去通過特定的方式取即可。SDWebImage就有這樣的一個類:SDImageCache。該類完美地幫助了我們解決了這個問題。

  使用的時候,我們首先要在使用的類里面做導入:

#import "SDImageCache.h"

然后就可以進行相關的操作了。讓我們直接看看SDImageCache.h文件:


@property (assign, nonatomic) NSUInteger maxMemoryCost;

/**
 * The maximum length of time to keep an image in the cache, in seconds
 */
@property (assign, nonatomic) NSInteger maxCacheAge;

/**
 * The maximum size of the cache, in bytes.
 */
@property (assign, nonatomic) NSUInteger maxCacheSize;

/**
 * Returns global shared cache instance
 *
 * @return SDImageCache global instance
 */
+ (SDImageCache *)sharedImageCache;

/**
 * Init a new cache store with a specific namespace
 *
 * @param ns The namespace to use for this cache store
 */
- (id)initWithNamespace:(NSString *)ns;

/**
 * Add a read-only cache path to search for images pre-cached by SDImageCache
 * Useful if you want to bundle pre-loaded images with your app
 *
 * @param path The path to use for this read-only cache path
 */
- (void)addReadOnlyCachePath:(NSString *)path;

/**
 * Store an image into memory and disk cache at the given key.
 *
 * @param image The image to store
 * @param key   The unique image cache key, usually it's image absolute URL
 */
- (void)storeImage:(UIImage *)image forKey:(NSString *)key;

/**
 * Store an image into memory and optionally disk cache at the given key.
 *
 * @param image  The image to store
 * @param key    The unique image cache key, usually it's image absolute URL
 * @param toDisk Store the image to disk cache if YES
 */
- (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;

/**
 * Store an image into memory and optionally disk cache at the given key.
 *
 * @param image       The image to store
 * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage
 * @param imageData   The image data as returned by the server, this representation will be used for disk storage
 *                    instead of converting the given image object into a storable/compressed image format in order
 *                    to save quality and CPU
 * @param key         The unique image cache key, usually it's image absolute URL
 * @param toDisk      Store the image to disk cache if YES
 */
- (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;

/**
 * Query the disk cache asynchronously.
 *
 * @param key The unique key used to store the wanted image
 */
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;

/**
 * Query the memory cache synchronously.
 *
 * @param key The unique key used to store the wanted image
 */
- (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;

/**
 * Query the disk cache synchronously after checking the memory cache.
 *
 * @param key The unique key used to store the wanted image
 */
- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;

/**
 * Remove the image from memory and disk cache synchronously
 *
 * @param key The unique image cache key
 */
- (void)removeImageForKey:(NSString *)key;


/**
 * Remove the image from memory and disk cache synchronously
 *
 * @param key             The unique image cache key
 * @param completionBlock An block that should be executed after the image has been removed (optional)
 */
- (void)removeImageForKey:(NSString *)key withCompletition:(void (^)())completion;

/**
 * Remove the image from memory and optionally disk cache synchronously
 *
 * @param key      The unique image cache key
 * @param fromDisk Also remove cache entry from disk if YES
 */
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;

/**
 * Remove the image from memory and optionally disk cache synchronously
 *
 * @param key             The unique image cache key
 * @param fromDisk        Also remove cache entry from disk if YES
 * @param completionBlock An block that should be executed after the image has been removed (optional)
 */
- (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletition:(void (^)())completion;

/**
 * Clear all memory cached images
 */
- (void)clearMemory;

/**
 * Clear all disk cached images. Non-blocking method - returns immediately.
 * @param completionBlock An block that should be executed after cache expiration completes (optional)
 */
- (void)clearDiskOnCompletion:(void (^)())completion;

/**
 * Clear all disk cached images
 * @see clearDiskOnCompletion:
 */
- (void)clearDisk;

/**
 * Remove all expired cached image from disk. Non-blocking method - returns immediately.
 * @param completionBlock An block that should be executed after cache expiration completes (optional)
 */
- (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock;

/**
 * Remove all expired cached image from disk
 * @see cleanDiskWithCompletionBlock:
 */
- (void)cleanDisk;

/**
 * Get the size used by the disk cache
 */
- (NSUInteger)getSize;

/**
 * Get the number of images in the disk cache
 */
- (NSUInteger)getDiskCount;

/**
 * Asynchronously calculate the disk cache's size.
 */
- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock;

/**
 * Check if image exists in cache already
 */
- (BOOL)diskImageExistsWithKey:(NSString *)key;

/**
 *  Get the cache path for a certain key (needs the cache path root folder)
 *
 *  @param key  the key (can be obtained from url using cacheKeyForURL)
 *  @param path the cach path root folder
 *
 *  @return the cache path
 */
- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;

/**
 *  Get the default cache path for a certain key
 *
 *  @param key the key (can be obtained from url using cacheKeyForURL)
 *
 *  @return the default cache path
 */
- (NSString *)defaultCachePathForKey:(NSString *)key;

  不要看着想吐就行。先看看使用吧。

 存圖片:

 SDImageCache *imageCache = [SDImageCache sharedImageCache];

   [imageCache storeImage:image forKey:@"myphoto" toDisk:YES];

取圖片:

 SDImageCache *imageCache = [SDImageCache sharedImageCache];
    UIImage *image = [imageCache imageFromDiskCacheForKey:@"myphoto"];

這樣就可以取到自己存的圖片了。可以看一下SDImageCache.h這個類了,里面提供了存圖片到內存和磁盤的方法,還有取圖片的方法,以及判斷該圖片是否存在的方法。還有就是刪除圖片、清空磁盤緩存、得到緩存大小等方法。

場景三、做設置中的清除緩存功能

  簡單來說,當我們點擊清除緩存按鈕的時候會觸發的消息如下:

- (void)clearCaches
{
    [MBProgressHUD showMessage:@"正在清理.."];
    
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDisk];

    [self performSelectorOnMainThread:@selector(cleanCacheSuccess) withObject:nil waitUntilDone:YES];
}

- (void)cleanCacheSuccess

 
         

{

 
         

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

 
         
 
         

        self.cacheLab.text = @"0.00M";

 
         

        return;

   });

 
         

}

很簡單,就是把使用SDWebImage緩存的圖片都清空就可以了,這里包括了內存中的緩存圖片以及磁盤上的緩存圖片。

 場景四、一個APP多用戶緩存存儲

  比如一個用戶下面有好多只屬於個人的圖片,那么如果我們想做到當切換用戶再切換當前用戶還可以看到原來用戶的圖片時,就可以用到SDImageCache的命名空間功能。其實很簡單

 1、簡單說一下:當我們使用SDImageCache去緩存圖片的時候,如果我們是這樣初始化的SDImageCache:

    SDImageCache *image = [SDImageCache sharedImageCache];

那么我們會在Caches(沙盒)文件夾下看到一個com.hackemist.SDWebImageCache.default文件夾,這里就是用來存儲sharedImageCache初始化的緩存存儲的圖片。如果我們是這樣初始化SDImageCache:

  SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"TTTTTT"];

那么我們會在Caches文件夾下看到一個com.hackemist.SDWebImageCache.TTTTT文件夾。這里就是用來存儲這樣初始化的緩存存儲的圖片。

其他看一下源碼可以知道,它是根據命名空間來命名文件夾的。

這樣我們就可以用用戶名作為命名空間名稱,這樣每次取緩存都用用戶名就OK了。

還有其他的使用場景,這里就不再贅述了。

四、實現原理 

 其實SDWebImage之所以能夠實現緩存的原理關鍵就是在哪個key值。

  比如我們在使用

- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;

的時候,其實就是把url當做了一個圖片的key值,然后存儲對應的圖片,如果下次請求的url和這次請求的url一樣,那么就直接根據url(這個key)來取圖片,如果url作為key的圖片緩存不存在,就去請求遠程服務器,然后請求過來之后再次將url和圖片對應,然后存儲。

 

五、總結

 

六、其他

  未完待續。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM