iOS如何获取网络图片(二)

时间:2023-12-01 15:35:14

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];
}