iOS开发网络篇—文件下载(二·合理)
一、边下载,边写入
1.思路
把下载的data追加到文件的尾部,直到所有的数据下载完为止。
1.在连通了服务器的时候,创建一个空的文件到沙盒中NSFileManager(文件管理类)
2.创建写数据的文件句柄
3.在接收到服务器返回的数据后,把data写入到创建的空文件中,但是不能使用writeTofile(会覆盖)
3.1移动到文件的尾部
3.2从当前移动的位置,写入数据
4.服务器的数据加载完毕后关闭连接,不再输入数据在文件中
二、代码示例
1 //
2 // YYViewController.m
3 // 01-文件的下载(不合理)
4 //
5 // Created by apple on 14-6-30.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import "YYViewController.h"
10
11 @interface YYViewController ()
12 @property(nonatomic,strong)NSMutableData *fileData;
13 @property(nonatomic,strong)NSFileHandle *writeHandle;
14 - (IBAction)star;
15
16 @end
17
18 @implementation YYViewController
19
20 - (void)viewDidLoad
21 {
22 [super viewDidLoad];
23 }
24
25 - (IBAction)star {
26 //创建下载路径
27
28 NSURL *url=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/resources/videosres.zip"];
29
30 //创建一个请求
31 NSURLRequest *request=[NSURLRequest requestWithURL:url];
32
33 //发送请求(使用代理的方式)
34 NSURLConnection *connt=[NSURLConnection connectionWithRequest:request delegate:self];
35 [connt start];
36 }
37
38 #pragma mark- NSURLConnectionDataDelegate代理方法
39 /*
40 *当接收到服务器的响应(连通了服务器)时会调用
41 */
42 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
43 {
44 //1.创建文件存数路径
45 NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
46 NSString *filePath=[caches stringByAppendingPathComponent:@"video.zip"];
47
48
49
50 //2.创建一个空的文件,到沙盒中
51 NSFileManager *mgr=[NSFileManager defaultManager];
52 //刚创建完毕的大小是o字节
53 [mgr createFileAtPath:filePath contents:nil attributes:nil];
54
55 //3.创建写数据的文件句柄
56 self.writeHandle=[NSFileHandle fileHandleForWritingAtPath:filePath];
57 }
58
59 /*
60 *当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)
61 */
62 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
63 {
64 //一点一点接收数据。
65 NSLog(@"接收到服务器的数据!---%d",data.length);
66 //把data写入到创建的空文件中,但是不能使用writeTofile(会覆盖)
67 //移动到文件的尾部
68 [self.writeHandle seekToEndOfFile];
69 //从当前移动的位置,写入数据
70 [self.writeHandle writeData:data];
71 }
72
73 /*
74 *当服务器的数据加载完毕时就会调用
75 */
76 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
77 {
78 NSLog(@"下载完毕");
79 //关闭连接,不再输入数据在文件中
80 [self.writeHandle closeFile];
81 }
82 /*
83 *请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误)
84 */
85 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
86 {
87 }
88 @end
注意点:
(1)创建文件存储路径(写入到沙盒)
NSString *caches=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath=[caches stringByAppendingPathComponent:@"video.zip"];
(2)创建一个空的文件夹( NSFileManager类的使用)
NSFileManager *mgr=[NSFileManager defaultManager];
(3)创建写数据的文件句柄
self.writeHandle=[NSFileHandle fileHandleForWritingAtPath:filePath];
(4)把data写入到创建的空文件中,但是不能使用writeTofile(会覆盖)
移动句柄到文件的尾部 [self.writeHandle seekToEndOfFile];
(5)下载完毕的时候,关闭连接
[self.writeHandle closeFile];