IOS-网络(大文件下载)
2016-02-01 13:59
435 查看
一、不合理方式
二、内存优化
三、断点续传
// // ViewController.m // IOS_0131_大文件下载 // // Created by ma c on 16/1/31. // Copyright © 2016年 博文科技. All rights reserved. // #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> //进度条 @property (weak, nonatomic) IBOutlet UIProgressView *progressView; //存数据 @property (nonatomic, strong) NSMutableData *fileData; //文件总长度 @property (nonatomic, assign) long long totalLength; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor cyanColor]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self download]; } - (void)download { //1.NSURL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_01.mp4"]; //2.请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.下载(创建完conn后会自动发起一个异步请求) [NSURLConnection connectionWithRequest:request delegate:self]; //[[NSURLConnection alloc] initWithRequest:request delegate:self]; //[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; //[conn start]; } #pragma mark - NSURLConnectionDataDelegate的代理方法 //请求失败时调用 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"didFailWithError"); } //接收到服务器响应就会调用 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { //NSLog(@"didReceiveResponse"); self.fileData = [NSMutableData data]; //取出文件的总长度 //NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response; //long long fileLength = [resp.allHeaderFields[@"Content-Length"] longLongValue]; self.totalLength = response.expectedContentLength; } //当接收到服务器返回的实体数据时就会调用(这个方法根据数据的实际大小可能被执行多次) - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //拼接数据 [self.fileData appendData:data]; //设置进度条(0~1) self.progressView.progress = (double)self.fileData.length / self.totalLength; NSLog(@"didReceiveData -> %ld",self.fileData.length); } //加载完毕时调用(服务器的数据完全返回后) - (void)connectionDidFinishLoading:(NSURLConnection *)connection { //NSLog(@"connectionDidFinishLoading"); //拼接文件路径 NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *file = [cache stringByAppendingPathComponent:@"minion_01.mp4"]; //NSLog(@"%@",file); //写到沙盒之中 [self.fileData writeToFile:file atomically:YES]; } @end
二、内存优化
// // ViewController.m // IOS_0201_大文件下载(合理方式) // // Created by ma c on 16/2/1. // Copyright © 2016年 博文科技. All rights reserved. // #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ///用来写数据的句柄对象 @property (nonatomic, strong) NSFileHandle *writeHandle; ///文件总大小 @property (nonatomic, assign) long long totalLength; ///当前已写入文件大小 @property (nonatomic, assign) long long currentLength; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor cyanColor]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self download]; } - (void)download { //1.NSURL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"]; //2.请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.下载(创建完conn后会自动发起一个异步请求) [NSURLConnection connectionWithRequest:request delegate:self]; } #pragma mark - NSURLConnectionDataDelegate的代理方法 //请求失败时调用 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { } //接收到服务器响应时调用 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { //文件路径 NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *file = [cache stringByAppendingPathComponent:@"minion_02.mp4"]; NSLog(@"%@",file); //创建一个空文件到沙盒中 NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager createFileAtPath:file contents:nil attributes:nil]; //创建一个用来写数据的文件句柄 self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:file]; //文件总大小 self.totalLength = response.expectedContentLength; } //接收到服务器数据时调用(根据文件大小,调用多次) - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //移动到文件结尾 [self.writeHandle seekToEndOfFile]; //写入数据 [self.writeHandle writeData:data]; //累计文件长度 self.currentLength += data.length; NSLog(@"下载进度-->%lf",(double)self.currentLength / self.totalLength); } //从服务器接收数据完毕时调用 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { self.currentLength = 0; self.totalLength = 0; //关闭文件 [self.writeHandle closeFile]; self.writeHandle = nil; } @end
三、断点续传
// // ViewController.m // IOS_0201_大文件下载(合理方式) // // Created by ma c on 16/2/1. // Copyright © 2016年 博文科技. All rights reserved. // #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ///用来写数据的句柄对象 @property (nonatomic, strong) NSFileHandle *writeHandle; ///连接对象 @property (nonatomic, strong) NSURLConnection *conn; ///文件总大小 @property (nonatomic, assign) long long totalLength; ///当前已写入文件大小 @property (nonatomic, assign) long long currentLength; - (IBAction)btnClick:(UIButton *)sender; @property (weak, nonatomic) IBOutlet UIButton *btnClick; @property (weak, nonatomic) IBOutlet UIProgressView *progressView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor cyanColor]; //设置进度条起始状态 self.progressView.progress = 0.0; } #pragma mark - NSURLConnectionDataDelegate的代理方法 //请求失败时调用 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { } //接收到服务器响应时调用 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { if (self.currentLength) return; //文件路径 NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *file = [cache stringByAppendingPathComponent:@"minion_02.mp4"]; NSLog(@"%@",file); //创建一个空文件到沙盒中 NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager createFileAtPath:file contents:nil attributes:nil]; //创建一个用来写数据的文件句柄 self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:file]; //文件总大小 self.totalLength = response.expectedContentLength; } //接收到服务器数据时调用(根据文件大小,调用多次) - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //移动到文件结尾 [self.writeHandle seekToEndOfFile]; //写入数据 [self.writeHandle writeData:data]; //累计文件长度 self.currentLength += data.length; //设置进度条进度 self.progressView.progress = (double)self.currentLength / self.totalLength; NSLog(@"下载进度-->%lf",(double)self.currentLength / self.totalLength); } //从服务器接收数据完毕时调用 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { self.currentLength = 0; self.totalLength = 0; //关闭文件 [self.writeHandle closeFile]; self.writeHandle = nil; //下载完成后,状态取反 self.btnClick.selected = !self.btnClick.isSelected; } - (IBAction)btnClick:(UIButton *)sender { //状态取反 sender.selected = !sender.isSelected; if (sender.selected) { //继续下载 //1.NSURL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"]; //2.请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //设置请求头 NSString *range = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength]; [request setValue:range forHTTPHeaderField:@"Range"]; //3.下载(创建完conn后会自动发起一个异步请求) self.conn = [NSURLConnection connectionWithRequest:request delegate:self]; } else { //暂停下载 [self.conn cancel]; self.conn = nil; } } @end
相关文章推荐
- linux tcp高并发
- LoadRunner做基于http协议的接口测试
- java 网络编程(五)----TCP进阶篇上传文本文件
- java 网络编程(四)----UDP进阶篇聊天小程序
- android studio编译android M时无法使用org.apache.http.**的解决方法
- dell 网络产品线
- 【性能诊断】StackOverflow引发的“网络”及系统稳定性问题
- php----http协议 Cookie
- 2016太原网络营销师谈一谈他对百度竞价的理解?
- android开发获取网络状态,wifi,wap,2g,3g.工具类(一)
- android开发网络连接工具类(一)
- 【infoQ】物联网项目的网络注意事项
- 利用CoreTelephony获取用户当前网络状态(判断2G,3G,4G)
- openstack(liberty):部署实验平台(一,基础网络环境搭建)
- java 网络编程(三)---TCP的基础级示例
- HTTPS 原理解析(转)
- TCP初始化序列号ISN
- java 网络编程(二)----UDP基础级的示例
- 网络模拟器WANem使用配置图文教程
- 两种请求方式URLHttpconnection 和Httpclient提交表单 网络篇(二)