当前位置: 移动技术网 > 移动技术>移动开发>IOS > IOS多线程实现多图片下载(二)

IOS多线程实现多图片下载(二)

2019年07月24日  | 移动技术网移动技术  | 我要评论

上篇文章给大家介绍了ios多线程实现多图片下载1,本文继续给大家介绍ios多线程下载图片。

这次是用多线程进行图片的下载与存储,而且考虑到下载失败,占位图片的问题(第一张就是下载失败的图片)

闲话少说,上代码吧,因为有一部分和上次的一样,所以这里只上传不一样的

先给大家展示下效果图:

依旧都是在viewcontroller.m中

1.

@interface viewcontroller ()
//所有数据
@property (nonatomic,strong)nsarray *apps;
//内存缓存图片
@property (nonatomic,strong)nsmutabledictionary *imgcache;
/**所有操作*/
@property (nonatomic,strong)nsmutabledictionary *operations;
/**队列对象*/
@property (nonatomic,strong) nsoperationqueue *queue;
@end 

前两个和前面的一致

operations使用来存储下载图片的线程操作的字典,主要作用是防止重复下载

queue则是使用多线程时用到的队列

2.

- (nsoperationqueue *)queue {
if (!_queue) {
_queue = [[nsoperationqueue alloc] init];
//最大并发数
_queue.maxconcurrentoperationcount = 3;
}
return _queue;
} 

对queue的初始化,以及控制子线程最多为3条

3.

- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath {
static nsstring *id = @"app";
uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:id];
ddzapp *app = self.apps[indexpath.row];
cell.textlabel.text = app.name;
cell.detailtextlabel.text = app.download;
//先从内存中取出图片
uiimage *image = self.imgcache[app.icon];
if (image) {
cell.imageview.image = image;
}else {
//内存中没有图片
//将图片文件数据写入到沙盒中
nsstring *cachespath = [nssearchpathfordirectoriesindomains(nscachesdirectory, nsuserdomainmask, yes) firstobject];
//获得文件名
nsstring *filename = [app.icon lastpathcomponent];
//计算出文件的全路径
nsstring *file = [cachespath stringbyappendingpathcomponent:filename];
//加载沙盒的文件数据
nsdata *data = [nsdata datawithcontentsoffile:file];
//判断沙盒中是否有图片
if (data) {
//直接加载沙盒中图片
uiimage *image = [uiimage imagewithdata:data];
cell.imageview.image = image;
//存到字典(内存)中
self.imgcache[app.icon] = image;
}else {
//下载图片
//占位图片
cell.imageview.image = [uiimage imagenamed:@"place.jpg"];
//先判断是否有下载任务
//加载失败后可以重复下载
nsoperation *operation = self.operations[app.icon];
if (operation == nil) {
//这张图片没有下载任务
operation = [nsblockoperation blockoperationwithblock:^{
nsdata *data = [nsdata datawithcontentsofurl:[nsurl urlwithstring:app.icon]];
//数据加载失败
if(data == nil) {
//移除操作
[self.operations removeobjectforkey:app.icon];
return ;
}
uiimage *image = [uiimage imagewithdata:data];
//存到内存中
self.imgcache[app.icon] = image;
//回到主线程显示图片
[[nsoperationqueue mainqueue] addoperationwithblock:^{
//会出现重复占位的问题
//cell.imageview.image = image;
//只需找到图片所在的行即可
[tableview reloadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationnone];
}];
//将图片数据写入到沙盒中
[data writetofile:file atomically:yes];
//移除操作
[self.operations removeobjectforkey:app.icon];
}];
//添加到下载队列
[self.queue addoperation:operation];
//添加到字典
self.operations[app.icon] = operation;
}
}
}
return cell;
}

这次绑定数据的方法内容有点多,因为考虑到了不少细节,不过逻辑和上次的差不多。

有关本文给大家介绍的ios多线程实现多图片下载2 ,小编就给大家介绍到这里,希望对大家有所帮助!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网