服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS多线程实现多图下载功能

iOS多线程实现多图下载功能

2021-04-22 18:01imkata IOS

这篇文章主要为大家详细介绍了iOS多线程实现多图下载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了iOS多线程实现多图下载功能的具体代码,供大家参考,具体内容如下

一.模型文件代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// XMGAPP.h
 
#import <Foundation/Foundation.h>
 
@interface XMGAPP : NSObject
 
/** APP的名称 */
@property (nonatomic, strong) NSString *name;
/** APP的图片的url地址 */
@property (nonatomic, strong) NSString *icon;
/** APP的下载量 */
@property (nonatomic, strong) NSString *download;
 
+(instancetype)appWithDict:(NSDictionary *)dict;
@end
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// XMGAPP.m
 
#import "XMGAPP.h"
 
@implementation XMGAPP
 
+(instancetype)appWithDict:(NSDictionary *)dict
{
  XMGAPP *appM = [[XMGAPP alloc]init];
  //KVC
  [appM setValuesForKeysWithDictionary:dict];
   
  return appM;
}
@end

控制器.m代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// ViewController.m
 
#import "ViewController.h"
#import "XMGAPP.h"
 
@interface ViewController ()
/** tableView的数据源 */
@property (nonatomic, strong) NSArray *apps;
/** 内存缓存 */
@property (nonatomic, strong) NSMutableDictionary *images;
/** 队列 */
@property (nonatomic, strong) NSOperationQueue *queue;
/** 操作缓存 */
@property (nonatomic, strong) NSMutableDictionary *operations;
@end
 
@implementation ViewController
 
#pragma mark ----------------------
#pragma mark lazy loading
-(NSOperationQueue *)queue
{
  if (_queue == nil) {
    _queue = [[NSOperationQueue alloc]init];
    //设置最大并发数
    _queue.maxConcurrentOperationCount = 5;
  }
  return _queue;
}
-(NSMutableDictionary *)images
{
  if (_images == nil) {
    _images = [NSMutableDictionary dictionary];
  }
  return _images;
}
-(NSArray *)apps
{
  if (_apps == nil) {
     
    //字典数组
    NSArray *arrayM = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"apps.plist" ofType:nil]];
     
    //字典数组---->模型数组
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSDictionary *dict in arrayM) {
      [arrM addObject:[XMGAPP appWithDict:dict]];
    }
    _apps = arrM;
  }
  return _apps;
}
 
-(NSMutableDictionary *)operations
{
  if (_operations == nil) {
    _operations = [NSMutableDictionary dictionary];
  }
  return _operations;
}
 
#pragma mark ----------------------
#pragma mark UITableViewDatasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  return 1;
}
 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return self.apps.count;
}
 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *ID = @"app";
   
  //1.创建cell
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
   
  //2.设置cell的数据
  //2.1 拿到该行cell对应的数据
  XMGAPP *appM = self.apps[indexPath.row];
   
  //2.2 设置标题
  cell.textLabel.text = appM.name;
   
  //2.3 设置子标题
  cell.detailTextLabel.text = appM.download;
   
  //2.4 设置图标
   
  //先去查看内存缓存中该图片时候已经存在,如果存在那么久直接拿来用,否则去检查磁盘缓存
  //如果有磁盘缓存,那么保存一份到内存,设置图片,否则就直接下载
  //1)没有下载过
  //2)重新打开程序
   
  UIImage *image = [self.images objectForKey:appM.icon];
  if (image) {
    cell.imageView.image = image;
    NSLog(@"%zd处的图片使用了内存缓存中的图片",indexPath.row) ;
  }else
  {
    //保存图片到沙盒缓存
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //获得图片的名称,不能包含/
    NSString *fileName = [appM.icon lastPathComponent];
    //拼接图片的全路径
    NSString *fullPath = [caches stringByAppendingPathComponent:fileName];
     
     
    //检查磁盘缓存
    NSData *imageData = [NSData dataWithContentsOfFile:fullPath];
    //废除
    imageData = nil;
     
    if (imageData) {
      UIImage *image = [UIImage imageWithData:imageData];
      cell.imageView.image = image;
       
      NSLog(@"%zd处的图片使用了磁盘缓存中的图片",indexPath.row) ;
      //把图片保存到内存缓存
      [self.images setObject:image forKey:appM.icon];
       
//      NSLog(@"%@",fullPath);
    }else
    {
      //检查该图片时候正在下载,如果是那么久什么都捕捉,否则再添加下载任务
      NSBlockOperation *download = [self.operations objectForKey:appM.icon];
      if (download) {
         
      }else
      {
         
        //先清空cell原来的图片
        cell.imageView.image = [UIImage imageNamed:@"Snip20160221_306"];
         
        download = [NSBlockOperation blockOperationWithBlock:^{
          NSURL *url = [NSURL URLWithString:appM.icon];
          NSData *imageData = [NSData dataWithContentsOfURL:url];
          UIImage *image = [UIImage imageWithData:imageData];
           
           NSLog(@"%zd--下载---",indexPath.row);
           
          //容错处理
          if (image == nil) {
            [self.operations removeObjectForKey:appM.icon];
            return ;
          }
          //演示网速慢的情况
          //[NSThread sleepForTimeInterval:3.0];
         
          //把图片保存到内存缓存
          [self.images setObject:image forKey:appM.icon];
           
          //NSLog(@"Download---%@",[NSThread currentThread]);
          //线程间通信
          [[NSOperationQueue mainQueue] addOperationWithBlock:^{
             
            //cell.imageView.image = image;
            //刷新一行
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
            //NSLog(@"UI---%@",[NSThread currentThread]);
          }];
           
           
          //写数据到沙盒
          [imageData writeToFile:fullPath atomically:YES];
           
          //移除图片的下载操作
          [self.operations removeObjectForKey:appM.icon];
           
        }];
         
        //添加操作到操作缓存中
        [self.operations setObject:download forKey:appM.icon];
         
        //添加操作到队列中
        [self.queue addOperation:download];
      }
       
    }
  }
   
  //3.返回cell
  return cell;
}
 
-(void)didReceiveMemoryWarning
{
  [self.images removeAllObjects];
   
  //取消队列中所有的操作
  [self.queue cancelAllOperations];
}
 
//1.UI很不流畅 --- > 开子线程下载图片
//2.图片重复下载 ---> 先把之前已经下载的图片保存起来(字典)
//内存缓存--->磁盘缓存
 
//3.图片不会刷新--->刷新某行
//4.图片重复下载(图片下载需要时间,当图片还未完全下载之前,又要重新显示该图片)
//5.数据错乱 ---设置占位图片
 
/*
 Documents:会备份,不允许
 Libray
  Preferences:偏好设置 保存账号
  caches:缓存文件
 tmp:临时路径(随时会被删除)
 */
 
@end

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/imkata/article/details/78898169

延伸 · 阅读

精彩推荐
  • IOSiOS10 Xcode8适配7个常见问题汇总

    iOS10 Xcode8适配7个常见问题汇总

    这篇文章主要为大家详细汇总了iOS10 Xcode8适配7个常见问题,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    索马里猫10332021-02-01
  • IOSIOS网络请求之AFNetWorking 3.x 使用详情

    IOS网络请求之AFNetWorking 3.x 使用详情

    本篇文章主要介绍了IOS网络请求之AFNetWorking 3.x 使用详情,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    总李写代码6892021-03-04
  • IOSiOS逆向教程之logify跟踪方法的调用

    iOS逆向教程之logify跟踪方法的调用

    这篇文章主要给大家介绍了关于iOS逆向教程之logify跟踪方法调用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学...

    Mr.Guo11472021-04-28
  • IOSiOS中时间与时间戳的相互转化实例代码

    iOS中时间与时间戳的相互转化实例代码

    这篇文章主要介绍了iOS中时间与时间戳的相互转化实例代码,非常具有实用价值,需要的朋友可以参考下。...

    张无忌!4812021-03-09
  • IOSiOS APP实现微信H5支付示例总结

    iOS APP实现微信H5支付示例总结

    这篇文章主要介绍了iOS APP实现微信H5支付示例总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下...

    一张小A11332021-06-01
  • IOS谈一谈iOS单例模式

    谈一谈iOS单例模式

    这篇文章主要和大家谈一谈iOS中的单例模式,单例模式是一种常用的软件设计模式,想要深入了解iOS单例模式的朋友可以参考一下...

    彭盛凇11872021-01-19
  • IOSiOS常见的几个修饰词深入讲解

    iOS常见的几个修饰词深入讲解

    这篇文章主要给大家介绍了关于iOS常见的几个修饰词的相关资料,iOS修饰词包括assign、weak、strong、retain、copy、nonatomic、atomic、readonly、readwrite,文中通过示...

    郡王丶千夜7422021-05-10
  • IOSxcode8提交ipa失败无法构建版本问题的解决方案

    xcode8提交ipa失败无法构建版本问题的解决方案

    xcode升级到xcode8后发现构建不了新的版本。怎么解决呢?下面小编给大家带来了xcode8提交ipa失败无法构建版本问题的解决方案,非常不错,一起看看吧...

    Cinna丶7542021-02-03