iOS如何获取网络图片(二)
2016-03-16 21:13
447 查看
ios如何获取图片(二)无沙盒下
解决问题
*解决问题1:tableView滑动卡顿,图片延时加载解决方法:添加异步请求,在子线程里请求网络,在主线程刷新UI
*解决问题2:反复请求网络图片,增加用户流量消耗
解决方法:创建了downloadImage,downloadImage属于数据源,当tableview滚动的时候就可以给cell的数据赋值,运用了MVC设计方式
*解决问题3:当没有请求到图片时,留白影响用户体验,图片还会延时刷新
解决方法:添加默认图片
*解决问题4:当该cell的网络请求未执行完,又滚动到了该cell,会导致网络请求重复
解决方法:创建网络请求缓冲池
*解决问题5:当出现数量较多的图片时,防止内存使用过多,耦合性大
解决方法:创建图片缓冲池
代码如下图
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { SXTShopCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier]; SXTShop * shop = self.dataList[indexPath.row]; cell.shop = shop; //为了避免重复加载的问题,创建了downloadImage,downloadImage属于数据源,当tableview滚动的时候就可以给cell的数据赋值 //从图片缓冲池里找到对应的图片 if ([self.imageCache objectForKey:shop.shop_image]) { //如果下载过,直接从内存中获取图片 cell.iconView.image = shop.downloadImage; cell.iconView.image = self.imageCache[shop.shop_image]; } else { //设置默认图片 cell.iconView.image = [UIImage imageNamed:@"defaultImage"]; [self downloadImage:indexPath]; } return cell; } - (void)downloadImage:(NSIndexPath *)indexPath { SXTShop * shop = self.dataList[indexPath.row]; if ([self.operationDict objectForKey:shop.shop_image]) { NSLog(@"已经请求过了,请等待下载"); } else { //如果未下载过,开启异步线程 NSBlockOperation * op = [NSBlockOperation blockOperationWithBlock:^{ //模拟网络延时 [NSThread sleepForTimeInterval:1]; //通过url获取网络数据 NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",baseUrl,shop.shop_image]]]; //将数据装换为图片 UIImage * image = [UIImage imageWithData:data]; //如果有图片 if (image) { //通知model,将图片赋值给downloadImage,以便下次从内存获取 // shop.downloadImage = image; //将图片作为value,将url作为key [self.imageCache setObject:image forKey:shop.shop_image]; //获取主队列,更新UI [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //刷新第indexPath单元的表格 [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone]; }]; } }]; //将请求加入操作缓冲池中 [self.operationDict setObject:op forKey:shop.shop_image]; //将请求加入全局队列 [self.queue addOperation:op]; } }
//当内存发生警报时,调用
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
[self.imageCache removeAllObjects]; [self.operationDict removeAllObjects]; [self.queue cancelAllOperations]; }
相关文章推荐
- Http Response Code[整理]
- JAVA中的TCP通信(多线程)
- 未能加载文件或程序集“System.Web.Http.WebHost, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e3
- [网络流24题]code vs 1916 负载平衡问题
- nginx使用ssl模块配置HTTPS支持
- 干货推荐:如何运维千台以上游戏云服务器——游族网络
- 模拟迅雷下载程序 多线程
- Android 网络连接判断与处理
- Cogs 12 运输问题2 (有上下界网络流)
- reachability ios网络连接判断
- 在tomcat7中启用HTTPS的详细配置
- 两步搞定 Tomcat 下启用 https:// 访问
- TCP/IP协议体系结构简介
- tcp连接中分组丢失情况分析
- TCP/IP 网络基础(一)
- Http client
- TCP三次握手
- 【深度学习】Dropout网络笔记
- 一些网络相关问题的总结
- 关于使用fseek函数之后feof函数无法结束文件的警告 http://bbs.csdn.net/topics/390759596