【iOS】网络加载图片缓存与SDWebImage

加载网络图片可以说是网络应用中必备的。如果单纯的去下载图片,而不去做多线程、缓存等技术去优化,加载图片时的效果与用户体验就会很差。

一、自己实现加载图片的方法

tips:

* iOS 中所有网络访问都是异步的 .( 自己 开线程去下载 )
* 普通 模型 增加 UIImage 属性 的方法做的是 内存缓存 ( 下次启动还需要从网络重新加载 ) , 而要做本地缓存的话 , 还要自己手动 存储网络上下载的图片 .
* 为了加快访问 , 还需要自己去弄 缓存 . ( 内存缓存或者本地缓存 )
* 当图片没有下载完成时,还要设置 占位图片

以下代码用NSOperation开异步线程下载图片,当下载完成时替换占位图片

//
//  XNViewController.m
//  加载网络图片, 普通的用NSOperation来做.
//
//  Created by neng on 14-7-7.
//  Copyright (c) 2014年 neng. All rights reserved.
//

#import "XNViewController.h"
#import "XNApp.h"

@interface XNViewController ()
@property (nonatomic, strong) NSArray *appList;
@property (nonatomic, strong) NSOperationQueue *queue;
@end

@implementation XNViewController
#pragma mark - 懒加载

- (NSOperationQueue *)queue {
	if (!_queue) _queue = [[NSOperationQueue alloc] init];
	return _queue;
}

//可抽取出来写到模型中
- (NSArray *)appList {
	if (!_appList) {
		//1.加载plist到数组中
		NSURL *url = [[NSBundle mainBundle] URLForResource:@"apps.plist" withExtension:nil];
		NSArray *array = [NSArray arrayWithContentsOfURL:url];
		//2.遍历数组
		NSMutableArray *arrayM = [NSMutableArray array];
		[array enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
		    [arrayM addObject:[XNApp appWithDict:obj]];  //数组中存放的是字典, 转换为app对象后再添加到数组
		}];
		_appList = [arrayM copy];
	}
	return _appList;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	self.tableView.rowHeight = 88;

//    NSLog(@"appList-%@",_appList);
}

#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.appList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *ID = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

	//用模型来填充每个cell
	XNApp *app = self.appList[indexPath.row];
	cell.textLabel.text = app.name;  //设置文字

	//设置图像: 模型中图像为nil时用默认图像,并下载图像. 否则用模型中的内存缓存图像.
	if (!app.image) {
		cell.imageView.image = [UIImage imageNamed:@"user_default"];

		[self downloadImg:indexPath];
	}
	else {
		//直接用模型中的内存缓存
		cell.imageView.image = app.image;
	}
//	NSLog(@"cell--%p", cell);

	return cell;
}

/**始终记住, 通过模型来修改显示. 而不要试图直接修改显示*/
- (void)downloadImg:(NSIndexPath *)indexPath {
	XNApp *app  = self.appList[indexPath.row]; //取得改行对应的模型

	[self.queue addOperationWithBlock: ^{
	    NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]]; //得到图像数据
	    UIImage *image = [UIImage imageWithData:imgData];

	    //在主线程中更新UI
	    [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
	        //通过修改模型, 来修改数据
	        app.image = image;
	        //刷新指定表格行
	        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
		}];
	}];
}

@end


上述代码只是做了内存缓存,而每次重新进入应用时,还会从网上重新下载。如果要继续优化上面的代码,需要自己去实现本地缓存。


二、使用第三方框架SDWebImage。(非常优秀)

* 特点 : 依赖的库很少 .功能全面。
* 自动实现 磁盘缓存 :
* 缓存图片名字是以 MD5 进行加密的 后的名字进行命名 .( 因为加密那堆字串是唯一的 )
* [imageView sd_setImageWithURL :v.fullImageURL   placeholderImage:[UIImage   imageNamed:@”xxxxx”]].
* 就一个方法就实现了 多线程 \ 带缓冲等效 . ( 可用带参数的方法 , 具体可看头文件 )

用SDWebImage修改上面的方法后的代码可简化为:
#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.appList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *ID = @"Cell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

	//用模型来填充每个cell
	XNApp *app = self.appList[indexPath.row];
	cell.textLabel.text = app.name;  //设置文字

//	//设置图像: 模型中图像为nil时用默认图像,并下载图像. 否则用模型中的内存缓存图像.
//	if (!cell.imageView.image) {
//		cell.imageView.image = [UIImage imageNamed:@"user_default"];
//
//		[self downloadImg:indexPath];
//	}
//	else {
//		//直接用模型中的内存缓存
//		cell.imageView.image = app.image;
//	}


	//使用SDWebImage来完成上面的功能. 针对ImageView.
	//一句话, 自动实现了异步下载. 图片本地缓存. 网络下载. 自动设置占位符.
	[cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"user_default"]];


	return cell;
}

/**始终记住, 通过模型来修改显示. 而不要试图直接修改显示*/
//- (void)downloadImg:(NSIndexPath *)indexPath {
//	XNApp *app  = self.appList[indexPath.row]; //取得改行对应的模型
//
//	[self.queue addOperationWithBlock: ^{
//	    NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:app.icon]]; //得到图像数据
//	    UIImage *image = [UIImage imageWithData:imgData];
//
//	    //在主线程中更新UI
//	    [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
//	        //通过修改模型, 来修改数据
//	        app.image = image;
//	        //刷新指定表格行
//	        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//		}];
//	}];
//}

@end

SDWebImage中的一些参数:
* SDWebImageRetryFailed = 1<< 0,    默认选项,失败后重试
* SDWebImageLowPriority = 1<< 1,     使用低优先级
* SDWebImageCacheMemoryOnly = 1<< 2,    仅仅使用内存缓存
* SDWebImageProgressiveDownload = 1<< 3,    显示现在进度
* SDWebImageRefreshCached = 1<< 4,     刷新缓存
* SDWebImageContinueInBackground =1 << 5,    后台继续下载图像
* SDWebImageHandleCookies = 1<< 6,     处理 Cookie
* SDWebImageAllowInvalidSSLCertificates= 1 << 7,     允许无效的 SSL 验证
* SDWebImageHighPriority = 1<< 8,      高优先级
* SDWebImageDelayPlaceholder = 1<< 9      延迟显示占位图片


转载请注明出处: http://blog.csdn.net/xn4545945   



  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值