@SDWebImage提供一个UIImageView的类别以支持加载来自网络的远程图片。具有缓存管理、异步下载、同一个URL下载次数控制和优化等特征.

@SDWebImage的导入
1.https://github.com/rs/SDWebImage 下载SDWebImage开源包
2.将类包拖入工程,再导入MapKit.framework、ImageIO.framework两个框架
3.SDWebImage是支持ARC的,在MRC的工程中要注意,可参考MRC工程配置ARC
4.注意:SDWebImage 3.0不向后兼容2.0并且最低需要iOS 5.0 的版本,而且提供的方法多数是Blcok形式

@目前来说,主要用到了"UIImageView+WebCache.h",给出一个代码示例:

        它是UIImageView的一个类目,在要使用它的类中加入#import "UIImageView+WebCache.h",调用                setImageWithURL:placeholderImage:方法。从异步下载到缓存管理,一切都会为你处理。

  1. - (void)createImageView{
  2. self.imageArray = [NSMutableArray array];
  3. self.urlArray = @[@"http://c.hiphotos.baidu.com/image/w%3D2048/sign=396e9d640b23dd542173a068e531b2de/cc11728b4710b9123a8117fec1fdfc039245226a.jpg",
  4. @"http://e.hiphotos.baidu.com/image/w%3D2048/sign=c9c32d60f1deb48ffb69a6dec4273b29/960a304e251f95cae5f125b7cb177f3e670952ae.jpg",
  5. @"http://f.hiphotos.baidu.com/image/w%3D2048/sign=0e0fe1d417ce36d3a20484300ecb3b87/3801213fb80e7bec015d1eef2d2eb9389b506b3c.jpg",
  6. @"http://a.hiphotos.baidu.com/image/w%3D2048/sign=6e8e7ce5b11c8701d6b6b5e613479f2f/b3fb43166d224f4a6059b1120bf790529922d1eb.jpg",
  7. @"http://f.hiphotos.baidu.com/image/w%3D2048/sign=e0608e290cf41bd5da53eff465e280cb/aec379310a55b31976baeb7741a98226cffc1774.jpg",
  8. @"http://g.hiphotos.baidu.com/image/w%3D2048/sign=4b5f112a0cf41bd5da53eff465e280cb/aec379310a55b319dd85747441a98226cffc17b6.jpg",
  9. @"http://h.hiphotos.baidu.com/image/w%3D2048/sign=35229123708b4710ce2ffaccf7f6c2fd/c995d143ad4bd113fc73de3058afa40f4bfb0571.jpg",
  10. @"http://b.hiphotos.baidu.com/image/w%3D2048/sign=ad8b74e88fb1cb133e693b13e96c574e/f9dcd100baa1cd11eba86d27bb12c8fcc3ce2d9e.jpg",
  11. @"http://e.hiphotos.baidu.com/image/w%3D2048/sign=ac1303f0a5efce1bea2bcfca9b69f2de/838ba61ea8d3fd1f7dc8e23c324e251f94ca5ff6.jpg",
  12. ];
  13. for (int i = 0; i < 3; i ++) {
  14. for (int j = 0; j < 3; j++) {
  15. UIImageView * imageView = [[UIImageView alloc]init];
  16. // 15 10 10 15
  17. imageView.frame = CGRectMake(15+100*j, 80+140*i, 90, 120);
  18. imageView.backgroundColor = [UIColor redColor];
  19. [self.view addSubview:imageView];
  20. [self.imageArray addObject:imageView];
  21. [imageView release];
  22. }
  23. }
  24. UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
  25. button.frame = CGRectMake(100, 510, 80, 40);
  26. [button setTitle:@"下载" forState:UIControlStateNormal];
  27. [button addTarget:self action:@selector(onClickLoadButton) forControlEvents:UIControlEventTouchUpInside];
  28. [self.view addSubview:button];
  29. }
  30. - (void)onClickLoadButton{
  31. //SDWebImageManager * manager = [SDWebImageManager sharedManager];
  32. for (int i = 0; i < [_imageArray count]; i++) {
  33. UIImageView * image = [_imageArray objectAtIndex:i];
  34. // 异步加载及缓存图片一步到位
  35. [image setImageWithURL:[NSURL URLWithString:[_urlArray objectAtIndex:i]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
  36. }
  37. }

查看图片是否进了缓存:

@得到1个图片的url用SDWebImage缓存后的文件名

  1. NSLog(@"%s__%d__|%@",__FUNCTION__,__LINE__,[[SDImageCache sharedImageCache] cachedFileNameForKey:@"http://c.hiphotos.baidu.com/image/w%3D2048/sign=396e9d640b23dd542173a068e531b2de/cc11728b4710b9123a8117fec1fdfc039245226a.jpg"]);

 

@其他

      SDWebImage是个比较大的类库,还有其他一些类的用法,自己不太了解,欢迎大家留言给出意见,一起学习,下面给出一些比较好的博客文章(转的)

      http://blog.csdn.net/shenjx1225/article/details/10444449

Using blocks

       使用blocks,你将被告知下载进度,完成时是成功还是失败:
// Here we use the new provided setImageWithURL: method to load the web image
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {... completion code here ...}];
       注意:如果请求被取消,那么block不会被调用(无论成功还是失败)。
 

Using SDWebImageManager

The SDWebImageManager is the class behind the UIImageView+WebCache category. It ties the asynchronous downloader with the image cache store. You can use this class directly to benefit from web image downloading with caching in another context than a UIView (ie: with Cocoa)

      下面是如何使用SDWebImageManager的代码:
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:imageURL
options:0
progress:^(NSUInteger receivedSize, long long expectedSize)
{
// progression tracking code
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
if (image)
{
// do something with image
}
}];
Using Asynchronous Image Downloader Independently
      也能够独立地使用异步图像下载:
[SDWebImageDownloader.sharedDownloader downloadImageWithURL:imageURL
options:0
progress:^(NSUInteger receivedSize, long long expectedSize)
{
// progression tracking code
}
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
{
if (image && finished)
{
// do something with image
}
}];
Using Asynchronous Image Caching Independently
        也可以独立地使用基于异步的图像缓存存储。SDImageCache维护一个内存缓存和一个可选的磁盘缓存。磁盘高
 
速缓存的写操作是异步进行的,所以它不会给UI增加不必要的延迟 。
        
        为了方便,SDImageCache类提供了一个单例,但是如果你想创建单独的缓存命名空间你也可以创建新的实例。
        你可以使用imageForKey:方法来查找缓存,如果返回为nil,说明当前图像不拥有缓存。因此你负责生成并缓存它。缓存键(cache key)是一个程序中图像缓存的唯一标识符,他通常是图像的url。
SDImageCache *imageCache = [SDImageCache.alloc initWithNamespace:@"myNamespace"];
[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
{
// image is not nil if image was found
}];
        默认情况下,如果一个图像不能在内存缓存中找到,SDImageCache将会查找高速缓存。你可以调用替代的方法imageFromMemoryCacheForKey:来预防这种情况的发生。
        存储一个图像到缓存,你可以使用storeImage:forKey: 方法:
[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
        默认情况下,图像将被存储在内存上的缓存以及磁盘上的缓存(异步)。
如果你想只在内存中缓存,使用替代方法storeImage:forKey:toDisk:,第三个参数为负数。

Using cache key filter

有时你也许不想使用图像URL作为缓存键,因为URL可能是动态的(i.e.: for access control purpose)。SDWebImageManager provides a way to set a cache key filter that takes the NSURL as input, and output a cache key NSString(这句不大理解)。

下面的示例在应用程序的委托中设置一个过滤器,在使用它的缓存键之前将从URL中删除任何查询字符串(The following example sets a filter in the application delegate that will remove any query-string from the URL before to use it as a cache key):

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
SDWebImageManager.sharedManager.cacheKeyFilter:^(NSURL *url)
{
url = [[[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path] autorelease];
return [url absoluteString];
}; // Your app init code...
return YES;
}

Using dynamic image size with UITableViewCell

UITableView通过第一个单元格设置的图像决定图像的尺寸。如果您的远程图像没有图像占位符的大小相同,您可能会遇到奇怪的变形缩放问题。下面的文章给出了一个方法来解决这个问题:

http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/

Handle image refresh(控制图像刷新)

默认情况下,SDWebImage确实非常积极的缓存。它忽略了所有类型的通过HTTP服务器返回的缓存控制头,并

 
且没有时间限制地缓存返回的图像。这意味着你的图像url是永远不会改变的、指向图像的静态url。如果指向的图片
 
发生了变化,那么url也会相应的跟着变化。

如果你不控制你的图像服务器,当它的内容更新时你不能改变它的url。Facebook头像就是这种情况的例子。在这种情况下,你可以使用SDWebImageRefreshCached的标志。这将稍微降低性能,但将会考虑到HTTP缓存控制头:

[imageView setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]
placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
options:SDWebImageRefreshCached];

Add a progress indicator(添加进度指示)

查看这个类别: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage

      @好像是SDWebImage2.0的流程介绍 http://blog.csdn.net/uxyheaven/article/details/7909373

iOS网络编程(三) 异步加载及缓存图片---->SDWebImage的更多相关文章

  1. Android新浪微博客户端(七)——ListView中的图片异步加载、缓存

    原文出自:方杰|http://fangjie.info/?p=193转载请注明出处 最终效果演示:http://fangjie.sinaapp.com/?page_id=54 该项目代码已经放到git ...

  2. [翻译]Bitmap的异步加载和缓存

    内容概述 [翻译]开发文档:android Bitmap的高效使用 本文内容来自开发文档"Traning > Displaying Bitmaps Efficiently", ...

  3. 【代码笔记】iOS-实现网络图片的异步加载和缓存

    代码: - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. se ...

  4. listview异步加载sd卡图片

    package com.example.gridview; import java.io.File; import java.io.FileOutputStream; import java.io.I ...

  5. Okhttp设置http缓存,在没有网络的情况下加载http缓存里面的内容

    HTTP_CACHE_FILENAME为缓存地址根路径: private final String HTTP_CACHE_FILENAME = "HttpCache"; priva ...

  6. 解决ListView滑动时卡的问题,实现异步加载图片解决

    ListView是最为常见的空间之一,现在的应用的呈现形式大多数都需要用到ListView来呈现,以列表的方式最直观最便于操作. 那么在使用的过程中大家一定使用adapter适配器来匹配这个ListV ...

  7. IOS学习之路二十三(EGOImageLoading异步加载图片开源框架使用)

    EGOImageLoading 是一个用的比较多的异步加载图片的第三方类库,简化开发过程,我们直接传入图片的url,这个类库就会自动帮我们异步加载和缓存工作:当从网上获取图片时,如果网速慢图片短时间内 ...

  8. 【Android】纯代码创建页面布局(含异步加载图片)

    开发环境:macOS 10.12 + Android Studio 2.2,MinSDK Android 5.1 先看看总体效果 本示例是基于Fragment进行的,直接上代码: [界面结构] 在 F ...

  9. Android-Universal-Image-Loader 图片异步加载类库的使用

    在博客中看到一篇利用组件进行图片异步加载的文章在此作记录 原文:http://blog.csdn.net/vipzjyno1/article/details/23206387 这个图片异步加载并缓存的 ...

随机推荐

  1. python 文件查找 glob

    glob模块是最简单的模块之一,内容非常少.用它可以查找符合特定规则的文件路径名.跟使用windows下的文件搜索差不多.查找文件只用到三个匹配符:"*", "?&quo ...

  2. opencv 操作本地摄像头实现录像

    直接上代码: // demo1.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <iostream> usin ...

  3. hdu 3483 A Very Simple Problem

    两种构造的方式都是正确的: 1. #include<cstdio> #include<cstring> #include<algorithm> #define ma ...

  4. Linux巡检

    # uname -a # 查看内核/操作系统/CPU信息 # head -n 1 /etc/issue # 查看操作系统版本 # cat /proc/cpuinfo # 查看CPU信息 # hostn ...

  5. TYPE C PD测试板 UFP测试板

  6. SQL Server中时间段查询

    /****** Script for SelectTopNRows command from SSMS ******/ select * from dbo.VehicleData20100901 wh ...

  7. html5 动画精灵

    <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8& ...

  8. 利用if,else判断输入的是不是一个正整数

    static void Main(string[] args)        {            while (true)                      { Console.Writ ...

  9. spring--DI--3

    3.1.1  依赖和依赖注入 传统应用程序设计中所说的依赖一般指“类之间的关系”,那先让我们复习一下类之间的关系: 泛化:表示类与类之间的继承关系.接口与接口之间的继承关系: 实现:表示类对接口的实现 ...

  10. NEsper z

    对实时信息分析和处理,常常需要客户应用程序的开发相应功能.一般地,这些功能需要提供以下的处理流程,分析获取的数据,筛选数据,提取出有用的信息,然后将其通过特定的形式展现出来.由于具体实时信息的高并发性 ...