一、不合理方式
1 // 2 // ViewController.m 3 // IOS_0131_大文件下载 4 // 5 // Created by ma c on 16/1/31. 6 // Copyright © 2016年 博文科技. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 11 @interface ViewController ()<NSURLConnectionDataDelegate> 12 13 //进度条 14 @property (weak, nonatomic) IBOutlet UIProgressView *progressView; 15 //存数据 16 @property (nonatomic, strong) NSMutableData *fileData; 17 //文件总长度 18 @property (nonatomic, assign) long long totalLength; 19 20 @end 21 22 @implementation ViewController 23 24 - (void)viewDidLoad { 25 [super viewDidLoad]; 26 27 self.view.backgroundColor = [UIColor cyanColor]; 28 } 29 30 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 31 { 32 [self download]; 33 } 34 35 - (void)download 36 { 37 //1.NSURL 38 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_01.mp4"]; 39 //2.请求 40 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 41 //3.下载(创建完conn后会自动发起一个异步请求) 42 [NSURLConnection connectionWithRequest:request delegate:self]; 43 44 //[[NSURLConnection alloc] initWithRequest:request delegate:self]; 45 //[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 46 //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; 47 //[conn start]; 48 } 49 #pragma mark - NSURLConnectionDataDelegate的代理方法 50 //请求失败时调用 51 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 52 { 53 NSLog(@"didFailWithError"); 54 } 55 //接收到服务器响应就会调用 56 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 57 { 58 //NSLog(@"didReceiveResponse"); 59 self.fileData = [NSMutableData data]; 60 61 //取出文件的总长度 62 //NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response; 63 //long long fileLength = [resp.allHeaderFields[@"Content-Length"] longLongValue]; 64 65 self.totalLength = response.expectedContentLength; 66 } 67 //当接收到服务器返回的实体数据时就会调用(这个方法根据数据的实际大小可能被执行多次) 68 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 69 { 70 //拼接数据 71 [self.fileData appendData:data]; 72 73 //设置进度条(0~1) 74 self.progressView.progress = (double)self.fileData.length / self.totalLength; 75 76 NSLog(@"didReceiveData -> %ld",self.fileData.length); 77 } 78 //加载完毕时调用(服务器的数据完全返回后) 79 - (void)connectionDidFinishLoading:(NSURLConnection *)connection 80 { 81 //NSLog(@"connectionDidFinishLoading"); 82 //拼接文件路径 83 NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 84 NSString *file = [cache stringByAppendingPathComponent:@"minion_01.mp4"]; 85 //NSLog(@"%@",file); 86 87 //写到沙盒之中 88 [self.fileData writeToFile:file atomically:YES]; 89 } 90 91 @end
二、内存优化
1 // 2 // ViewController.m 3 // IOS_0201_大文件下载(合理方式) 4 // 5 // Created by ma c on 16/2/1. 6 // Copyright © 2016年 博文科技. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 11 @interface ViewController ()<NSURLConnectionDataDelegate> 12 13 ///用来写数据的句柄对象 14 @property (nonatomic, strong) NSFileHandle *writeHandle; 15 ///文件总大小 16 @property (nonatomic, assign) long long totalLength; 17 ///当前已写入文件大小 18 @property (nonatomic, assign) long long currentLength; 19 20 @end 21 22 @implementation ViewController 23 24 - (void)viewDidLoad { 25 [super viewDidLoad]; 26 27 self.view.backgroundColor = [UIColor cyanColor]; 28 29 } 30 31 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 32 { 33 [self download]; 34 } 35 36 - (void)download 37 { 38 //1.NSURL 39 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"]; 40 //2.请求 41 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 42 //3.下载(创建完conn后会自动发起一个异步请求) 43 [NSURLConnection connectionWithRequest:request delegate:self]; 44 45 } 46 #pragma mark - NSURLConnectionDataDelegate的代理方法 47 //请求失败时调用 48 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 49 { 50 51 } 52 //接收到服务器响应时调用 53 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 54 { 55 //文件路径 56 NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 57 NSString *file = [cache stringByAppendingPathComponent:@"minion_02.mp4"]; 58 NSLog(@"%@",file); 59 //创建一个空文件到沙盒中 60 NSFileManager *fileManager = [NSFileManager defaultManager]; 61 [fileManager createFileAtPath:file contents:nil attributes:nil]; 62 63 //创建一个用来写数据的文件句柄 64 self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:file]; 65 66 //文件总大小 67 self.totalLength = response.expectedContentLength; 68 69 } 70 //接收到服务器数据时调用(根据文件大小,调用多次) 71 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 72 { 73 //移动到文件结尾 74 [self.writeHandle seekToEndOfFile]; 75 //写入数据 76 [self.writeHandle writeData:data]; 77 //累计文件长度 78 self.currentLength += data.length; 79 NSLog(@"下载进度-->%lf",(double)self.currentLength / self.totalLength); 80 81 } 82 //从服务器接收数据完毕时调用 83 - (void)connectionDidFinishLoading:(NSURLConnection *)connection 84 { 85 86 self.currentLength = 0; 87 self.totalLength = 0; 88 //关闭文件 89 [self.writeHandle closeFile]; 90 self.writeHandle = nil; 91 92 } 93 @end
三、断点续传
1 // 2 // ViewController.m 3 // IOS_0201_大文件下载(合理方式) 4 // 5 // Created by ma c on 16/2/1. 6 // Copyright © 2016年 博文科技. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 11 @interface ViewController ()<NSURLConnectionDataDelegate> 12 13 ///用来写数据的句柄对象 14 @property (nonatomic, strong) NSFileHandle *writeHandle; 15 ///连接对象 16 @property (nonatomic, strong) NSURLConnection *conn; 17 18 ///文件总大小 19 @property (nonatomic, assign) long long totalLength; 20 ///当前已写入文件大小 21 @property (nonatomic, assign) long long currentLength; 22 23 - (IBAction)btnClick:(UIButton *)sender; 24 @property (weak, nonatomic) IBOutlet UIButton *btnClick; 25 26 @property (weak, nonatomic) IBOutlet UIProgressView *progressView; 27 28 @end 29 30 @implementation ViewController 31 32 - (void)viewDidLoad { 33 [super viewDidLoad]; 34 35 self.view.backgroundColor = [UIColor cyanColor]; 36 //设置进度条起始状态 37 self.progressView.progress = 0.0; 38 39 } 40 41 #pragma mark - NSURLConnectionDataDelegate的代理方法 42 //请求失败时调用 43 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 44 { 45 46 } 47 //接收到服务器响应时调用 48 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 49 { 50 if (self.currentLength) return; 51 //文件路径 52 NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 53 NSString *file = [cache stringByAppendingPathComponent:@"minion_02.mp4"]; 54 NSLog(@"%@",file); 55 //创建一个空文件到沙盒中 56 NSFileManager *fileManager = [NSFileManager defaultManager]; 57 [fileManager createFileAtPath:file contents:nil attributes:nil]; 58 59 //创建一个用来写数据的文件句柄 60 self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:file]; 61 62 //文件总大小 63 self.totalLength = response.expectedContentLength; 64 65 } 66 //接收到服务器数据时调用(根据文件大小,调用多次) 67 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 68 { 69 //移动到文件结尾 70 [self.writeHandle seekToEndOfFile]; 71 //写入数据 72 [self.writeHandle writeData:data]; 73 //累计文件长度 74 self.currentLength += data.length; 75 //设置进度条进度 76 self.progressView.progress = (double)self.currentLength / self.totalLength; 77 78 NSLog(@"下载进度-->%lf",(double)self.currentLength / self.totalLength); 79 80 81 } 82 //从服务器接收数据完毕时调用 83 - (void)connectionDidFinishLoading:(NSURLConnection *)connection 84 { 85 86 self.currentLength = 0; 87 self.totalLength = 0; 88 //关闭文件 89 [self.writeHandle closeFile]; 90 self.writeHandle = nil; 91 //下载完成后,状态取反 92 self.btnClick.selected = !self.btnClick.isSelected; 93 } 94 95 - (IBAction)btnClick:(UIButton *)sender { 96 //状态取反 97 sender.selected = !sender.isSelected; 98 if (sender.selected) { //继续下载 99 //1.NSURL 100 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"]; 101 //2.请求 102 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 103 104 //设置请求头 105 NSString *range = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength]; 106 [request setValue:range forHTTPHeaderField:@"Range"]; 107 108 //3.下载(创建完conn后会自动发起一个异步请求) 109 self.conn = [NSURLConnection connectionWithRequest:request delegate:self]; 110 111 } else { //暂停下载 112 [self.conn cancel]; 113 self.conn = nil; 114 115 } 116 117 } 118 @end