iOS開發之加載大量網絡圖片優化

一、概述
編程

在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)異步加載app

(3)加載完畢前使用佔位圖片框架

二、優化方法
異步

方法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     延遲顯示佔位圖片

相關文章
相關標籤/搜索