一、不合理方式

 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

转载于:https://www.cnblogs.com/oc-bowen/p/5175207.html

IOS-网络(大文件下载)相关推荐

  1. iOS网络缓存扫盲篇--使用两行代码就能完成80%的缓存需求

    原文地址:https://github.com/ChenYilong/ParseSourceCodeStudy/blob/master/02_Parse的网络缓存与离线存储/iOS网络缓存扫盲篇.md ...

  2. [深入浅出Cocoa]iOS网络编程之Socket

    一,iOS网络编程层次模型 在前文<深入浅出Cocoa之Bonjour网络编程>中我介绍了如何在Mac系统下进行 Bonjour 编程,在那篇文章中也介绍过 Cocoa 中网络编程层次结构 ...

  3. iOS网络编程开发—HTTP协议

    iOS网络编程开发-HTTP协议 说明:apache tomcat服务器必须占用8080端口 一.URL 1.基本介绍 URL的全称是Uniform Resource Locator(统一资源定位符) ...

  4. 【多线程编程学习】java多线程基于数据分割的大文件下载器

    文章目录 代码:基于数据分割的大文件下载器 作为包装的存储对象类: 主文件下载类: 子任务下载类: 处理缓存: 启动类: 数据分割思想产生的问题 代码来自书籍<java多线程编程实战指南> ...

  5. iOS网络编程之Socket

    [深入浅出Cocoa]iOS网络编程之Socket 罗朝辉 (http://blog.csdn.net/kesalin) CC 许可,转载请注明出处 更多 Cocoa 开发文章,敬请访问<深入浅 ...

  6. 大文件下载及视频点播的CDN加速实践

    简介:为了帮助用户更好地了解和使用CDN产品,CDN应用实践进阶系统课程开课啦!前几天,阿里云CDN产品专家陈智城在线分享了<大文件下载及视频点播的CDN加速实践>议题,解读大文件下载和视 ...

  7. [深入浅出Cocoa]iOS网络编程之NSStream

    2019独角兽企业重金招聘Python工程师标准>>> [深入浅出Cocoa]iOS网络编程之NSStream 目录(?)[+] [深入浅出Cocoa]iOS网络编程之NSStrea ...

  8. java 大文件下载_Java大文件下载不全问题

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 各位同学好,目前碰到一个问题,Java平台下载大文件下载一部分就结束不能全部下载,有可能是网络问题造成下载中断,请问大家有什么解决办法吗,或者有遇到类似问 ...

  9. python 全栈开发,Day36(作业讲解(大文件下载以及进度条展示),socket的更多方法介绍,验证客户端链接的合法性hmac,socketserver)...

     先来回顾一下昨天的内容 黏包现象 粘包现象的成因 : tcp协议的特点 面向流的 为了保证可靠传输 所以有很多优化的机制 无边界 所有在连接建立的基础上传递的数据之间没有界限 收发消息很有可能不完全 ...

  10. javascript 大文件下载,分片下载,断点续传

    javascript 大文件下载,分片下载,断点续传 文章目录 javascript 大文件下载,分片下载,断点续传 1:获取文件大小: 2:切片下载 3:合并数据 4:下载到本地 5:成功 6:完整 ...

最新文章

  1. android 入门之一【开发环境搭建】
  2. CTFshow php特性 web142
  3. 微信小程序想要最短服务路径
  4. command对象的ExecuteScalar方法
  5. Android获取通讯录速度,在android中获取联系人非常慢
  6. Linux的进程优先级NI和PR
  7. DevExpress中XtraGrid控件对GridView每行的颜色设置 zt
  8. 趣学 C 语言(六)—— 结构和联合
  9. stm32呼吸灯程序_STM32裸机开发基础篇02点亮LED
  10. java连接数据库实现基本的增删改查
  11. MATLAB 数据拟合方法
  12. select2使用问题--删除添加select2的DOM
  13. linux之U盘读写速度测试
  14. HIVE厂牌艺人_北京音乐节-北京音乐节全攻略 - 马蜂窝
  15. 2021年化工自动化控制仪表考试题库及化工自动化控制仪表报名考试
  16. Windows 7 Service Pack 1已发布:但是您应该安装它吗?
  17. D3D9利用顶点缓冲区绘制三角形
  18. SQL查询语句注入实战(手注,显注)
  19. IOS开发入门之二——第一个App
  20. 同翔网浅析RoCE网络技术

热门文章

  1. java.io.IOException: Broken pipe 的异常处理
  2. php获取flash上传视频文件大小,php解析flash文件(.swf文件)获取其长度和宽度
  3. 以太网性能测试仪应该具备什么功能?
  4. 鸿蒙和安卓,到底有什么区别?
  5. 程序语言的组成知识笔记
  6. 硬件:关于CPU超频知识笔记
  7. phpstudy页面不存在_网站的404页面对于SEO的重要作用
  8. Linux系统文件编程(1)
  9. mysql读书笔记---if语句
  10. 「Vueconf」探索 Vue3 中 的 JSX