首先,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中看到其他的方法,和上边的方法类似,读者自行查看即可。

//包含了多种功能
1,sd_setImageWithURL获取网络图片
2,placeholderImage占位图片
3,progress 下载进度 用法: NSLog(@"下载进步:%f",(double)receivedSize / expectedSize);
4, *image *error *imageURL分别完成后返回的图片,错误和下载地址
5,SDImageCacheType cacheType 是枚举类型,图片存储位置在内存、磁盘或无
6,SDWebImageOptions 枚举类型 用法:SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPrioritySDWebImageRetryFailed 下载失败重复下载        常用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'

 }];

场景二、使用它做本地缓存

  很多时候我们可能拍照得到的一张图片要多个地方使用,那么我们就希望可以把这张图片放到缓存里面,然后每次用这张图片的时候就去通过特定的方式取即可。SDWebImage就有这样的一个类:SDImageCache。该类完美地帮助了我们解决了这个问题。

  使用的时候,我们首先要在使用的类里面做导入:

  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;

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

存图:

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

取图:

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

// 这样就可以取到自己存的图片了。可以看一下SDImageCache.h这个类了,里面提供了存图片到内存和磁盘的方法,还有取图片的方法,以及判断该图片是否存在的方法。还有就是删除图片、清空磁盘缓存、得到缓存大小等方法。

场景二、做设置中的清除缓存功能

简单来说,当我们点击清除缓存按钮的时候会触发的消息如下:

 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 1112 { 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; 1920  }); 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;

五、其他

- (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 = ;

  未完待续。

转载于:https://www.cnblogs.com/xjy-123/p/5205339.html

SDWebImage的简单使用相关推荐

  1. SDWebImage 的简单使用方法

    第一步,下载SDWebImage,导入工程.github托管地址https://github.com/rs/SDWebImage 第二步,在需要的地方导入头文件 1 #import   "U ...

  2. iOS-常用的第三方框架的介绍

    写iOS 程序的时候往往需要很多第三方框架的支持,可以大大减少工作量,讲重点放在软件本身的逻辑实现上. GitHub 里面有大量优秀的第三方框架,而且 License 对商业很友好.一下摘录一下几乎每 ...

  3. iOS常用的第三方类库

    在iOS开发中不可避免的会用到一些第三方类库,它们提供了很多实用的功能,使我们的开发变得更有效率:同时,也可以从它们的源代码中学习到很多有用的东西. Reachability 检测网络连接 用来检查网 ...

  4. SDWebImage开源库阅读分析(全)

    汇总记录: 本文基于SDWebImage 4.2.3版本进行分析和整理(链接地址). 整体目录结构: SDWebImage |----SDWebImageCompat 处理不同平台(iOS.TV.OS ...

  5. SDWebImage

    2019独角兽企业重金招聘Python工程师标准>>> #import "ViewController.h" #import "UIImageView+ ...

  6. SDWebImage中文说明

    前端时间想详细的了解下AFNetworking库,所以想着看看官方的API吧.想想既然看看就做下笔记吧,既然做了笔记为何不试着翻译一下呢.然后就有了之前的文章<AFNetworking说明书&g ...

  7. 模仿SDWebImage实现异步加载图片

    模仿SDWebImage实现异步加载图片 SDWebImage想必大家都不陌生吧,要实现它的图片异步加载功能这个还是很简单的. 注意:此处我只实现了异步加载图片,并没有将文件缓存到本地的打算哦:) 源 ...

  8. iOS SDWebImage 缓存机制与缓存策略

    2019独角兽企业重金招聘Python工程师标准>>> 一.SDWebImage 缓存机制 1.基本用法 SDWebImage提供一个UIImageView的Category,用来加 ...

  9. iOS开发——你真的会用SDWebImage?

    http://www.cocoachina.com/ios/20160503/16064.html 本文授权转载,作者:hosea_zhou(简书) SDWebImage作为目前最受欢迎的图片下载第三 ...

  10. SDWebImage实现分析

    该博文来自南峰子的技术博客,文章从下载和缓存俩个大的组件分析到里面一些核心方法的实现,条理清晰,相对于一些一上来就通篇分析实现思路的技术文章, 这篇的讲解思路明确,框架架构也讲的比较清楚. 看完这篇再 ...

最新文章

  1. 菜鸟配置SAMBA服务之4
  2. 中国北斗全球系统核心星座将于2019年年底部署完成
  3. bzoj 36733674 可持久化并查集加强版(可持久化线段树+启发式合并)
  4. 在物理内存中观察CLR托管内存及GC行为
  5. php 类加载,关于PHP中类的加载
  6. mysql5.7 no password_MySQL5.7.20报错Access denied for user 'root'@'localhost' (using password: NO)
  7. Dockerfile最佳实践(二)
  8. oracle脑裂的判断机制,Keepalived两节点出现双VIP的情况(脑裂)
  9. 【转】64位win7环境eclipse集成svn后出现Failed to load JavaHL Library的解决办法
  10. matlab 不确定度计算器,不确定度计算器
  11. 每天一个小技巧【1】·TextMeshPro的中文设置
  12. java 读取excel数据
  13. 模拟集成电路设计与分析——全差分放大器
  14. 获取当前月份的最后一天
  15. C#正则表达式匹配任意字符
  16. 11张图揭露了程序员的日常生活,看完笑哭(泪奔)!
  17. springboot easyexcel不创建对象导入excel 通用版
  18. android 4.2 webview,java-Android(4.4)WebView第二次加载时不显示ifra...
  19. 计算机游戏活动总结,关于亲子游戏活动总结最新三篇
  20. 小周的考研计划(一定要上岸呀)

热门文章

  1. 澜舟科技开源轻量级中文语言预训练模型——孟子模型
  2. 【论文】PathQG: 基于事实的神经问题生成
  3. 【NLTK基础】一文轻松使用NLTK进行NLP任务(附视频)
  4. estimator 模型保存与使用
  5. 02 ZooKeeper分布式集群安装
  6. pandas—pandas.DataFrame.iterrows的使用
  7. numpy—np.info(function)
  8. 机器学习入门——机器学习基础概念
  9. 别再对 Istio 一脸懵了,万众期待的第一本 Istio 著作现!已!上!市
  10. 深入搜索引擎的关键——索引