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

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

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

  很多时候我们可能拍照得到的一张图片要多个地方使用,那么我们就希望可以把这张图片放到缓存里面,然后每次用这张图片的时候就去通过特定的方式取即可。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'提示框框架
[MBProgressHUD showMessage:@"正在清理.."];
4
5 [[SDImageCache sharedImageCache] clearMemory];
6 [[SDImageCache sharedImageCache] clearDisk];
7
8 [self performSelectorOnMainThread:@selector(cleanCacheSuccess) withObject:nil waitUntilDone:YES];
}
- (void)cleanCacheSuccess
11
{ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ self.cacheLab.text = @"0.00M"; return;
19
}); }

实现原理:

  //其实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其他功能

,设置定期清理缓存时间    

//设置100天,默认是7天
[SDWebImageManager sharedManager].imageCache.maxCacheAge = * * *
,设置最大缓存容量 //无默认值,单位目前不清楚
[SDWebImageManager sharedManager].imageCache.maxCacheSize = ;

  未完待续。

SDWebImage的简单使用的更多相关文章

  1. SDWebImage 的简单使用方法

    第一步,下载SDWebImage,导入工程 第二步,在需要的地方导入头文件:#import   "UIImageView+WebCache.h" 第三步,调用sd_setImage ...

  2. AJ学IOS 之微博项目实战(8)用AFNetworking和SDWebImage简单加载微博数据

    AJ分享,必须精品 一:效果 没有图文混排,也没有复杂的UI,仅仅是简单的显示出微博数据,主要介绍AFNetworking和SDWebImage的简单用法 二:加载数据AFNetworking AFN ...

  3. SDWebImage 详解

    一.SDWebImage介绍 1.在项目的开发过程中,我们经常会用到异步加载图片的功能,先从网络上异步下载图片,然后通过UIImageView显示在屏幕上.这是一个经常使用的功能,基本上所有的联网应用 ...

  4. SDWebImage原理小结

    先贴上github上的地址:https://github.com/rs/SDWebImage,至于安装方式这里就不多说了,它的框架说明中都有,不过建议使用cocoaPod来安装比较好,方便日后的维护代 ...

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

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

  6. iOS开发常用的第三方类库

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

  7. GitHub 里面有大量优秀的第三方框架

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

  8. 【转】iOS开发常用的第三方类库

    原文: http://blog.csdn.net/xiazailushang/article/details/9716043 在iOS开发中不可避免的会用到一些第三方类库,它们提供了很多实用的功能,使 ...

  9. iOS开发之常用第三方框架(下载地址,使用方法,总结)

    iOS开发之常用第三方框架(下载地址,使用方法,总结) 说句实话,自学了这么久iOS,如果说我不知道的但是又基本上都摸遍了iOS相关知识,但是每次做项目的时候,遇到难一点的地方或者没试过的东西就闷了. ...

随机推荐

  1. 成吨提高开发效率:Intellij Shortcuts精简子集与思维模式

    在线精简cheatsheet备查表:intellij.linesh.twGithub项目:intellij-mac-frequent-keymap Intellij的快捷键多而繁杂,从官方推荐的key ...

  2. 数据库插入数据返回当前主键ID值方法

    当我们插入一条数据的时候,我们很多时候都想立刻获取当前插入的主键值返回以做它用.我们通常的做法有如下几种: 1. 先 select max(id) +1 ,然后将+1后的值作为主键插入数据库: 2. ...

  3. jquery禁用下拉框

    禁用下拉框 //下拉框禁用 $("select").each(function () { $("#" + this.id).attr("disable ...

  4. arcengine中自定义工具和自带工具条(ICommand)点击后和其他工具使用的冲突

    自己系统中本身对于放大缩小等功能直接是单独重写的,但是如果在加一个工具条具有相同功能的话两者之间会有一些冲突,为解决该冲突可以重写工具条的OnItemClick事件 该工具条命名为axTool 我本身 ...

  5. Scrapy开发指南

    一.Scrapy简介 Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中. Scrapy基于事件驱动网络框架 Twis ...

  6. [deviceone开发]-Star分享的几个示例

    一.简介 这个是star早期分享的几个示例,都非常实用,包括弹出的菜单,模拟支付密码输入等.初学者推荐.也可以直接使用.二.效果图 三.相关下载 https://github.com/do-proje ...

  7. 深入理解javascript选择器API系列第三篇——h5新增的3种selector方法

    × 目录 [1]方法 [2]非实时 [3]缺陷 前面的话 尽管DOM作为API已经非常完善了,但是为了实现更多的功能,DOM仍然进行了扩展,其中一个重要的扩展就是对选择器API的扩展.人们对jQuer ...

  8. Xcode8+和iOS10+使用Masonry自动计算行高

    说起tableView的自动计算行高,真的是不想再提了,写了不知道几百遍了.可就是这麽一个小玩意儿,把我给难的不行不行的,眼看都要没头发了. 1.设置tableView的预估行高和行高为自动计算 // ...

  9. webservice入门实例,CXF方式

    1.下载CXF,及先关jar包. CXF 下载地址:http://cxf.apache.org/download.html,选择"File"列中的zip格式下载.解压后可以看到一些 ...

  10. JSON金额解析BUG的解决过程

    [原创申明:文章为原创,欢迎非盈利性转载,但转载必须注明来源] 这是在我们开发的一个支付系统中暴露的一个BUG,问题本身比较简单,有意思的是解决问题的过程.将过程分享出来,希望能够对大家有所帮助. 一 ...