ios网络图片加载优化

栏目: 编程语言 · IOS · 发布时间: 7年前

内容简介:在IOS下通过URL读一张网络图片并不像其他编程语言那样可以直接把图片路径放到图片路径的位置就ok,而是需要我们通过一段类似流的方式去加载网络图片,接着才能把图片放入图片路径显示。加载网络图片可以说是网络应用中必备的。如果单纯的去下载图片,而不去做多线程、缓存等技术去优化,加载图片时的效果与用户体验就会很差。

1、概述

IOS 下通过URL读一张网络图片并不像其他 编程语言 那样可以直接把图片路径放到图片路径的位置就ok,而是需要我们通过一段类似流的方式去加载网络图片,接着才能把图片放入图片路径显示。比如:

-(UIImage *) getImageFromURL:(NSString *)fileURL {
  //NSLog(@"执行图片下载函数");    
  UIImage * result;    
  NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
  result = [UIImage imageWithData:data];    
  return result;
}

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

优化思路为:

  • (1)本地缓存

  • (2)异步加载

  • (3)加载完毕前使用占位图片

2、优化方法

方法1:用NSOperation开异步线程下载图片,当下载完成时替换占位图片

#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

上述代码只是做了内存缓存,还没有做本地缓存,因为这里这种方法不是重点,也不是首选方法。上面代码每次重新进入应用时,还会从网上重新下载。如果要继续优化上面的代码,需要自己去实现本地缓存。

方法2:使用第三方框架SDWebImage

特点:

依赖的库很少,功能全面。

自动实现磁盘缓存:缓存图片名字是以MD5进行加密的后的名字进行命名.(因为加密那堆字串是唯一的)

加载网络图片时直接设置占位图片:

[imageView sd_setImageWithURL:imageurl  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     延迟显示占位图片

以上所述就是小编给大家介绍的《ios网络图片加载优化》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

.NET设计规范

.NET设计规范

克瓦林纳 / 葛子昴 / 人民邮电出版社 / 2006-7 / 49.00元

本书为框架设计师和广大开发人员设计高质量的软件提供了权威的指南。书中介绍了在设计框架时的最佳实践,提供了自顶向下的规范,其中所描述的规范普遍适用于规模不同、可重用程度不同的框架和软件。这些规范历经.net框架三个版本的长期开发,凝聚了数千名开发人员的经验和智慧。微软的各开发组正在使用这些规范开发下一代影响世界的软件产品。. 本书适用于框架设计师以及相关的专业技术人员,也适用于高等院校相关专业......一起来看看 《.NET设计规范》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具