标签:
iOS开发网络篇—文件下载(六·压缩和解压)
一、完成文件下载
需求:完成文件下载
1.在本地服务器中,添加一个图片的压缩文件。

2.代码示例:
文件下载器代码:
头文件
1 // 2 // YYfileDownloader.h 3 // 01-文件的下载(不合理) 4 // 5 // Created by apple on 14-7-1. 6 // Copyright (c) 2014年 itcase. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 @interface YYfileDownloader : NSObject 12 //下载的远程url(连接到服务器的路径) 13 @property(nonatomic,strong)NSString *url; 14 //下载后的存储路径(文件下载到什么地方) 15 @property(nonatomic,strong)NSString *destPath; 16 //是否正在下载(只有下载器内部清楚) 17 @property(nonatomic,readonly,getter = isDownloading)BOOL Downloading; 18 //用来监听下载进度 19 @property(nonatomic,copy)void (^progressHandler)(double progress); 20 //用来监听下载完成 21 @property(nonatomic,copy)void (^completionHandler)(); 22 //用来监听下载错误 23 @property(nonatomic,copy)void(^failureHandler)(NSError *error); 24 -(void)pause; 25 -(void)start; 26 @end
实现代码:
1 //
2 // YYfileDownloader.m
3 // 01-文件的下载(不合理)
4 //
5 // Created by apple on 14-7-1.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import "YYfileDownloader.h"
10
11 @interface YYfileDownloader ()<NSURLConnectionDataDelegate>
12 //请求对象
13 @property(nonatomic,strong)NSURLConnection *cnnt;
14 //文件句柄
15 @property(nonatomic,strong)NSFileHandle *writeHandle;
16 //当前获取到的数据长度
17 @property(nonatomic,assign)long long currentLength;
18 //完整数据长度
19 @property(nonatomic,assign)long long sumLength;
20
21 @end
22 @implementation YYfileDownloader
23 //开始下载
24 -(void)start
25 {
26 _Downloading=YES;
27
28 //创建一个请求
29 NSURL *URL=[NSURL URLWithString:self.url];
30 NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];
31
32 //设置请求头信息
33 //self.currentLength字节部分重新开始读取
34 NSString *value=[NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
35 [request setValue:value forHTTPHeaderField:@"Range"];
36
37 //发送请求(使用代理的方式)
38 self.cnnt=[NSURLConnection connectionWithRequest:request delegate:self];
39
40 }
41
42 //暂停下载
43 -(void)pause
44 {
45 _Downloading=NO;
46 //取消发送请求
47 [self.cnnt cancel];
48 self.cnnt=nil;
49 }
50
51 #pragma mark- NSURLConnectionDataDelegate代理方法
52 /*
53 *当接收到服务器的响应(连通了服务器)时会调用
54 */
55 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
56 {
57 #warning 判断是否是第一次连接
58 if (self.sumLength) return;
59
60 //1.创建文件存数路径
61 NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
62 NSString *filePath=[caches stringByAppendingPathComponent:@"images.zip"];
63
64
65
66 //2.创建一个空的文件,到沙盒中
67 NSFileManager *mgr=[NSFileManager defaultManager];
68 //刚创建完毕的大小是o字节
69 [mgr createFileAtPath:filePath contents:nil attributes:nil];
70
71 //3.创建写数据的文件句柄
72 self.writeHandle=[NSFileHandle fileHandleForWritingAtPath:filePath];
73
74 //4.获取完整的文件长度
75 self.sumLength=response.expectedContentLength;
76 }
77
78 /*
79 *当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)
80 */
81 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
82 {
83 //累加接收到的数据长度
84 self.currentLength+=data.length;
85 //计算进度值
86 double progress=(double)self.currentLength/self.sumLength;
87 // self.progress.progress=progress;
88 if (self.progressHandler) {//传递进度值给block
89 self.progressHandler(progress);
90
91 //相当于在此处调用了下面的代码
92 // ^(double progress)
93 // {
94 // //把进度的值,传递到控制器中进度条,以进行显示
95 // vc.progress.progress=progress;
96 // };
97 }
98
99
100 //一点一点接收数据。
101 NSLog(@"接收到服务器的数据!---%d",data.length);
102 //把data写入到创建的空文件中,但是不能使用writeTofile(会覆盖)
103 //移动到文件的尾部
104 [self.writeHandle seekToEndOfFile];
105 //从当前移动的位置,写入数据
106 [self.writeHandle writeData:data];
107 }
108
109 /*
110 *当服务器的数据加载完毕时就会调用
111 */
112 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
113 {
114 NSLog(@"下载完毕----%lld",self.sumLength);
115 //关闭连接,不再输入数据在文件中
116 [self.writeHandle closeFile];
117 self.writeHandle=nil;
118
119 //清空进度值
120 self.currentLength=0;
121 self.sumLength=0;
122
123 if (self.completionHandler) {//下载完成通知控制器
124 self.completionHandler();
125 //相当于下面的代码
126 // ^{
127 // NSLog(@"下载完成");
128 // [self.btn setTitle:@"下载已经完成" forState:UIControlStateNormal];
129 // }
130 }
131
132 }
133 /*
134 *请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误)
135 */
136 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
137 {
138 if (self.failureHandler) {//通知控制器,下载出错
139 self.failureHandler(error);
140 //相当于调用了下面的代码
141 // ^{
142 // NSLog(@"下载错误!");
143 // }
144 }
145 }
146
147 @end
主控制器中的控制代码:
1 //
2 // YYViewController.m
3 // 01-文件下载(解压)
4 //
5 // Created by apple on 14-7-2.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import "YYViewController.h"
10 #import "YYfileDownloader.h"
11
12 @interface YYViewController ()
13 @property(nonatomic,strong)YYfileDownloader *fileDownloader;
14 //@property (weak, nonatomic) IBOutlet UIButton *btn;
15 @property (weak, nonatomic) IBOutlet UIProgressView *progress;
16 @end
17
18 @implementation YYViewController
19
20 - (void)viewDidLoad
21 {
22 [super viewDidLoad];
23 }
24
25 #pragma mark-懒加载
26 -(YYfileDownloader *)fileDownloader
27 {
28 if (_fileDownloader==nil) {
29 _fileDownloader=[[YYfileDownloader alloc]init];
30 //设置文件下载路径
31 _fileDownloader.url=@"http://192.168.1.53:8080/MJServer/resources/images.zip";
32
33 //设置文件保存路径
34 NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
35 NSString *filePath=[caches stringByAppendingPathComponent:@"images.zip"];
36 _fileDownloader.destPath=filePath;
37
38 _fileDownloader.progressHandler=^(double progress)
39 {
40 NSLog(@"下载进度-----%f",progress);
41 };
42 _fileDownloader.completionHandler=^{
43 NSLog(@"下载完成");
44 //下载完成后,对文件进行解压
45
46 };
47 _fileDownloader.failureHandler=^(NSError *error){
48 NSLog(@"下载错误!%@",error);
49 };
50 }
51 return _fileDownloader;
52 }
53
54 //当手指触摸屏幕的时候,下载压缩文件
55 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
56 {
57 [self.fileDownloader start];
58 }
59
60
61 @end
3.打印查看:

在沙盒中,查看下载到的数据。

二、实现解压
需求:下载完成后,对文件实现解压
说明:这里使用一个纯C语言的库进行解压。
1.第三方解压框架介绍:
第三方解压缩框架——SSZipArchive
下载地址:https://github.com/samsoffes/ssziparchive
注意:需要引入libz.dylib框架
(1)解压
NSString *zipPath = @"path_to_your_zip_file";
NSString *destinationPath = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath];
(2) 压缩
NSString *zippedPath = @"path_where_you_want_the_file_created";
NSArray *inputPaths = [NSArray arrayWithObjects:
[[NSBundle mainBundle] pathForResource:@"photo1" ofType:@"jpg"],
[[NSBundle mainBundle] pathForResource:@"photo2" ofType:@"jpg"]nil];
[SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];
(3)图示

2.使用:
(1)导入第三方框架

(2)导入头文件
(3)点击直接运行会报错。原因是它缺乏一个库,这个框架的使用依赖于libz.dylib这个库,需要导入这个库才能使用。

(4)运行程序,代码示例
解压功能实现代码如下:
1 //
2 // YYViewController.m
3 // 01-文件下载(解压)
4 //
5 // Created by apple on 14-7-2.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import "YYViewController.h"
10 #import "YYfileDownloader.h"
11 #import "SSZipArchive.h"
12
13 @interface YYViewController ()
14 @property(nonatomic,strong)YYfileDownloader *fileDownloader;
15 //@property (weak, nonatomic) IBOutlet UIButton *btn;
16 @property (weak, nonatomic) IBOutlet UIProgressView *progress;
17 @end
18
19 @implementation YYViewController
20
21 - (void)viewDidLoad
22 {
23 [super viewDidLoad];
24 }
25
26 #pragma mark-懒加载
27 -(YYfileDownloader *)fileDownloader
28 {
29 if (_fileDownloader==nil) {
30 _fileDownloader=[[YYfileDownloader alloc]init];
31 //设置文件下载路径
32 _fileDownloader.url=@"http://192.168.1.53:8080/MJServer/resources/images.zip";
33
34 //设置文件保存路径
35 NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
36 NSString *filePath=[caches stringByAppendingPathComponent:@"images.zip"];
37 _fileDownloader.destPath=filePath;
38
39 _fileDownloader.progressHandler=^(double progress)
40 {
41 NSLog(@"下载进度-----%f",progress);
42 };
43 _fileDownloader.completionHandler=^{
44 NSLog(@"下载完成");
45 //下载完成后,对文件进行解压
46 //使用第三方框架,对下载的压缩文件进行解压
47 //注意:如果文件较大的话,解压过程会比较耗时,所以最好把它放到异步线程去执行
48 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
49 //参数说明:第一个参数为要解压的文件路径,第二个参数为解压后的文件保存路径
50 [SSZipArchive unzipFileAtPath:filePath toDestination:caches];
51 NSLog(@"-----%@",[NSThread currentThread]);
52 NSLog(@"已经解压完成!");
53 });
54
55 };
56 _fileDownloader.failureHandler=^(NSError *error){
57 NSLog(@"下载错误!%@",error);
58 };
59 }
60 return _fileDownloader;
61 }
62
63 //当手指触摸屏幕的时候,下载压缩文件
64 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
65 {
66 [self.fileDownloader start];
67 }
68
69
70 @end
查看沙盒:

打印查看:

三、压缩文件
需求:把图片压缩后,写入到沙盒缓存中
1.向项目中添加图片,以备演示

2.示例代码
1 //
2 // YYViewController.m
3 // 01-文件下载(解压)
4 //
5 // Created by apple on 14-7-2.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import "YYViewController.h"
10 #import "YYfileDownloader.h"
11 #import "SSZipArchive.h"
12
13 @interface YYViewController ()
14 @property(nonatomic,strong)YYfileDownloader *fileDownloader;
15 //@property (weak, nonatomic) IBOutlet UIButton *btn;
16 @property (weak, nonatomic) IBOutlet UIProgressView *progress;
17 @end
18
19 @implementation YYViewController
20
21 //当手指触摸屏幕的时候,对文件进行压缩
22 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
23 {
24 // [self.fileDownloader start];
25 // [[NSBundle mainBundle]pathForResource:@"minion_01.png" ofType:nil];
26 // [[NSBundle mainBundle]pathForResource:@"minion_01.png" ofType:nil];
27
28 //1.获取mainBundle中的所有png图片
29 NSArray *pngs=[[NSBundle mainBundle]pathsForResourcesOfType:@"png" inDirectory:nil];
30
31 NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
32 NSString *filePath=[caches stringByAppendingPathComponent:@"img.zip"];
33 //第一个参数为压缩后的文件路径,第二个参数为压缩的文件数组
34 [SSZipArchive createZipFileAtPath:filePath withFilesAtPaths:pngs];
35
36 }
37
38
39 @end
查看沙盒:

注意:路径一定能要是全路径。
标签:
原文地址:http://www.cnblogs.com/junhuawang/p/4388561.html