SDWebImage的簡單使用

首先,SDWebImage的git地址是:https://github.com/rs/SDWebImage。咱們能夠直接到這裏進行下載,而後添加到本身的項目中去。git

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

一、場景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中看到其餘的方法,和上邊的方法相似,讀者自行查看便可。服務器

 

//包含了多種功能
1,sd_setImageWithURL獲取網絡圖片
2,placeholderImage佔位圖片
3,progress 下載進度 用法: NSLog(@"下載進步:%f",(double)receivedSize / expectedSize);
4, *image *error *imageURL分別完成後返回的圖片,錯誤和下載地址
5,SDImageCacheType cacheType 是枚舉類型,圖片存儲位置在內存、磁盤或無
6,SDWebImageOptions 枚舉類型 
    用法:SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPriority
    SDWebImageRetryFailed 下載失敗重複下載        經常使用
    SDWebImageLowPriority 當UI交互的時候暫停下載   經常使用
    SDWebImageCacheMemoryOnly 只存圖片在內存
    SDWebImageProgressiveDownload 能夠像瀏覽器那樣從上往下下載刷新圖片 
    SDWebImageRefreshCached 刷新緩存
    SDWebImageHighPriority  高優先級
    SDWebImageDelayPlaceholder 不加載佔位圖    
//示例tableview的cell: [cell.imageView sd_setImageWithURL:(NSURL
*)placeholderImage:(UIImage *)options:(SDWebImageOptions)progress:^(NSInteger receivedSize, NSInteger expectedSize) { //'receivedSize'已經接收了多少數據大小
//'
expectedSize'服務器上文件大小
 } completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType,NSURL *imageURL) { 
// '
image'下載完成後自動轉成的image圖片
// 'error'返回錯誤
// 'cacheType'緩存類型
// 'imageURL'

}];

 

 

 

場景2、使用它作本地緩存網絡

  不少時候咱們可能拍照獲得的一張圖片要多個地方使用,那麼咱們就但願能夠把這張圖片放到緩存裏面,而後每次用這張圖片的時候就去經過特定的方式取便可。SDWebImage就有這樣的一個類:SDImageCache。該類完美地幫助了咱們解決了這個問題。app

  使用的時候,咱們首先要在使用的類裏面作導入:框架

 

  1 #import "SDImageCache.h"
  2 而後就能夠進行相關的操做了。讓咱們直接看看SDImageCache.h文件:
  3 
  4 
  5 @property (assign, nonatomic) NSUInteger maxMemoryCost;
  6 
  7 /**
  8  * The maximum length of time to keep an image in the cache, in seconds
  9  */
 10 @property (assign, nonatomic) NSInteger maxCacheAge;
 11 
 12 /**
 13  * The maximum size of the cache, in bytes.
 14  */
 15 @property (assign, nonatomic) NSUInteger maxCacheSize;
 16 
 17 /**
 18  * Returns global shared cache instance
 19  *
 20  * @return SDImageCache global instance
 21  */
 22 + (SDImageCache *)sharedImageCache;
 23 
 24 /**
 25  * Init a new cache store with a specific namespace
 26  *
 27  * @param ns The namespace to use for this cache store
 28  */
 29 - (id)initWithNamespace:(NSString *)ns;
 30 
 31 /**
 32  * Add a read-only cache path to search for images pre-cached by SDImageCache
 33  * Useful if you want to bundle pre-loaded images with your app
 34  *
 35  * @param path The path to use for this read-only cache path
 36  */
 37 - (void)addReadOnlyCachePath:(NSString *)path;
 38 
 39 /**
 40  * Store an image into memory and disk cache at the given key.
 41  *
 42  * @param image The image to store
 43  * @param key   The unique image cache key, usually it's image absolute URL
 44  */
 45 - (void)storeImage:(UIImage *)image forKey:(NSString *)key;
 46 
 47 /**
 48  * Store an image into memory and optionally disk cache at the given key.
 49  *
 50  * @param image  The image to store
 51  * @param key    The unique image cache key, usually it's image absolute URL
 52  * @param toDisk Store the image to disk cache if YES
 53  */
 54 - (void)storeImage:(UIImage *)image forKey:(NSString *)key toDisk:(BOOL)toDisk;
 55 
 56 /**
 57  * Store an image into memory and optionally disk cache at the given key.
 58  *
 59  * @param image       The image to store
 60  * @param recalculate BOOL indicates if imageData can be used or a new data should be constructed from the UIImage
 61  * @param imageData   The image data as returned by the server, this representation will be used for disk storage
 62  *                    instead of converting the given image object into a storable/compressed image format in order
 63  *                    to save quality and CPU
 64  * @param key         The unique image cache key, usually it's image absolute URL
 65  * @param toDisk      Store the image to disk cache if YES
 66  */
 67 - (void)storeImage:(UIImage *)image recalculateFromImage:(BOOL)recalculate imageData:(NSData *)imageData forKey:(NSString *)key toDisk:(BOOL)toDisk;
 68 
 69 /**
 70  * Query the disk cache asynchronously.
 71  *
 72  * @param key The unique key used to store the wanted image
 73  */
 74 - (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock;
 75 
 76 /**
 77  * Query the memory cache synchronously.
 78  *
 79  * @param key The unique key used to store the wanted image
 80  */
 81 - (UIImage *)imageFromMemoryCacheForKey:(NSString *)key;
 82 
 83 /**
 84  * Query the disk cache synchronously after checking the memory cache.
 85  *
 86  * @param key The unique key used to store the wanted image
 87  */
 88 - (UIImage *)imageFromDiskCacheForKey:(NSString *)key;
 89 
 90 /**
 91  * Remove the image from memory and disk cache synchronously
 92  *
 93  * @param key The unique image cache key
 94  */
 95 - (void)removeImageForKey:(NSString *)key;
 96 
 97 
 98 /**
 99  * Remove the image from memory and disk cache synchronously
100  *
101  * @param key             The unique image cache key
102  * @param completionBlock An block that should be executed after the image has been removed (optional)
103  */
104 - (void)removeImageForKey:(NSString *)key withCompletition:(void (^)())completion;
105 
106 /**
107  * Remove the image from memory and optionally disk cache synchronously
108  *
109  * @param key      The unique image cache key
110  * @param fromDisk Also remove cache entry from disk if YES
111  */
112 - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk;
113 
114 /**
115  * Remove the image from memory and optionally disk cache synchronously
116  *
117  * @param key             The unique image cache key
118  * @param fromDisk        Also remove cache entry from disk if YES
119  * @param completionBlock An block that should be executed after the image has been removed (optional)
120  */
121 - (void)removeImageForKey:(NSString *)key fromDisk:(BOOL)fromDisk withCompletition:(void (^)())completion;
122 
123 /**
124  * Clear all memory cached images
125  */
126 - (void)clearMemory;
127 
128 /**
129  * Clear all disk cached images. Non-blocking method - returns immediately.
130  * @param completionBlock An block that should be executed after cache expiration completes (optional)
131  */
132 - (void)clearDiskOnCompletion:(void (^)())completion;
133 
134 /**
135  * Clear all disk cached images
136  * @see clearDiskOnCompletion:
137  */
138 - (void)clearDisk;
139 
140 /**
141  * Remove all expired cached image from disk. Non-blocking method - returns immediately.
142  * @param completionBlock An block that should be executed after cache expiration completes (optional)
143  */
144 - (void)cleanDiskWithCompletionBlock:(void (^)())completionBlock;
145 
146 /**
147  * Remove all expired cached image from disk
148  * @see cleanDiskWithCompletionBlock:
149  */
150 - (void)cleanDisk;
151 
152 /**
153  * Get the size used by the disk cache
154  */
155 - (NSUInteger)getSize;
156 
157 /**
158  * Get the number of images in the disk cache
159  */
160 - (NSUInteger)getDiskCount;
161 
162 /**
163  * Asynchronously calculate the disk cache's size.
164  */
165 - (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, NSUInteger totalSize))completionBlock;
166 
167 /**
168  * Check if image exists in cache already
169  */
170 - (BOOL)diskImageExistsWithKey:(NSString *)key;
171 
172 /**
173  *  Get the cache path for a certain key (needs the cache path root folder)
174  *
175  *  @param key  the key (can be obtained from url using cacheKeyForURL)
176  *  @param path the cach path root folder
177  *
178  *  @return the cache path
179  */
180 - (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;
181 
182 /**
183  *  Get the default cache path for a certain key
184  *
185  *  @param key the key (can be obtained from url using cacheKeyForURL)
186  *
187  *  @return the default cache path
188  */
189 - (NSString *)defaultCachePathForKey:(NSString *)key;

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

存圖:this

 SDImageCache *imageCache = [SDImageCache sharedImageCache];
   [imageCache storeImage:image forKey:@"myphoto" toDisk:YES];

取圖:

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

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

場景2、作設置中的清除緩存功能

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

 1 - (void)clearCaches
 2 {
//使用了'
MBProgressHUD'提示框框架
3 [MBProgressHUD showMessage:@"正在清理.."];
4

5
[[SDImageCache sharedImageCache] clearMemory];
6
[[SDImageCache sharedImageCache] clearDisk];
7

8
[self performSelectorOnMainThread:@selector(cleanCacheSuccess) withObject:nil waitUntilDone:YES];
9 }
10 - (void)cleanCacheSuccess
11
12 {
13
14 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
15
16 self.cacheLab.text = @"0.00M";
17
18 return;
19
20 });
21
22 }

實現原理:

  //其實SDWebImage之因此可以實現緩存的原理關鍵就是在哪一個key值。   //好比咱們在使用的時候,其實就是把url當作了一個圖片的key值,而後存儲對應的圖片,若是下次請求的url和此次請求的url同樣,那麼就直接根據url(這個key)來取圖片,若是url做爲key的圖片緩存不存在,就去請求遠程服務器,而後請求過來以後再次將url和圖片對應,而後存儲。
- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url andPlaceholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;

5、其餘

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    SDWebImageManager *mrg = [SDWebImageManager sharedManager];
    //1,取消下載操做
    [mrg cancelAll];
    //2,清除內存緩存
    [mrg.imageCache clearMemory];
}
3其餘功能

1,設置按期清理緩存時間    

//設置100天,默認是7天
[SDWebImageManager sharedManager].imageCache.maxCacheAge = 100 * 24 * 60 * 60
2,設置最大緩存容量

//無默認值,單位目前不清楚
[SDWebImageManager sharedManager].imageCache.maxCacheSize = ;

 

  未完待續。

相關文章
相關標籤/搜索