#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView; @property (nonatomic, assign) NSInteger totalSize;
@property (nonatomic, assign) NSInteger currentSize;
/** 文件句柄*/
@property (nonatomic, strong)NSFileHandle *handle;
/** 沙盒路径 */
@property (nonatomic, strong) NSString *fullPath;
/** 连接对象 */
@property (nonatomic, strong) NSURLConnection *connect;
@end @implementation ViewController - (IBAction)startBtnClick:(id)sender {
[self download];
}
- (IBAction)cancelBtnClick:(id)sender {
[self.connect cancel];
}
- (IBAction)goOnBtnClick:(id)sender {
[self download];
} //内存飙升
-(void)download
{
//1.url
// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w%3D580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"]; NSURL *url = [NSURL URLWithString:@"http://www.33lc.com/article/UploadPic/2012-10/2012102514201759594.jpg"]; //2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //设置请求头信息,告诉服务器值请求一部分数据range
/*
bytes=0-100
bytes=-100
bytes=0- 请求100之后的所有数据
*/
NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentSize];
[request setValue:range forHTTPHeaderField:@"Range"];
NSLog(@"+++++++%@",range); //3.发送请求
NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:request delegate:self];
self.connect = connect;
} #pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse"); //1.得到文件的总大小(本次请求的文件数据的总大小 != 文件的总大小)
// self.totalSize = response.expectedContentLength + self.currentSize; if (self.currentSize >) {
return;
} self.totalSize = response.expectedContentLength; //2.写数据到沙盒中
self.fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.jpg"]; NSLog(@"%@",self.fullPath); //3.创建一个空的文件
[[NSFileManager defaultManager] createFileAtPath:self.fullPath contents:nil attributes:nil]; //NSDictionary *dict = [[NSFileManager defaultManager]attributesOfItemAtPath:self.fullPath error:nil]; //4.创建文件句柄(指针)
self.handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath];
} -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//1.移动文件句柄到数据的末尾
[self.handle seekToEndOfFile]; //2.写数据
[self.handle writeData:data]; //3.获得进度
self.currentSize += data.length; //进度=已经下载/文件的总大小
NSLog(@"%f",1.0 * self.currentSize/self.totalSize);
self.progressView.progress = 1.0 * self.currentSize/self.totalSize;
//NSLog(@"%@",self.fullPath);
} -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
} -(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//1.关闭文件句柄
[self.handle closeFile];
self.handle = nil; NSLog(@"connectionDidFinishLoading");
NSLog(@"%@",self.fullPath);
}
@end

#####6.0  大文件断点下载

(1)实现思路

在下载文件的时候不再是整块的从头开始下载,而是看当前文件已经下载到哪个地方,然后从该地方接着往后面下载。可以通过在请求对象中设置请求头实现。

(2)解决方案(设置请求头)

```

//2.创建请求对象

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//2.1 设置下载文件的某一部分

// 只要设置HTTP请求头的Range属性, 就可以实现从指定位置开始下载

/*

表示头500个字节:Range: bytes=0-499

表示第二个500字节:Range: bytes=500-999

表示最后500个字节:Range: bytes=-500

表示500字节以后的范围:Range: bytes=500-

*/

NSString *range = [NSString stringWithFormat:@"bytes=%zd-",self.currentLength];

[request setValue:range forHTTPHeaderField:@"Range"];

```

(3)注意点(下载进度并判断是否需要重新创建文件)

```objc

//获得当前要下载文件的总大小(通过响应头得到)

NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;

//注意点:res.expectedContentLength获得是本次请求要下载的文件的大小(并非是完整的文件的大小)

//因此:文件的总大小 == 本次要下载的文件大小+已经下载的文件的大小

self.totalLength = res.expectedContentLength + self.currentLength;

NSLog(@"----------------------------%zd",self.totalLength);

//0 判断当前是否已经下载过,如果当前文件已经存在,那么直接返回

if (self.currentLength >0) {

return;

}

```

ios开发网络学习四:NSURLConnection大文件断点下载的更多相关文章

  1. ios开发网络学习十一:NSURLSessionDataTask离线断点下载(断点续传)

    #import "ViewController.h" #define FileName @"121212.mp4" @interface ViewControl ...

  2. ios开发网络学习五:MiMEType ,多线程下载文件思路,文件的压缩和解压缩

    一:MiMEType:一般可以再百度上搜索到相应文件的MiMEType,或是利用c语言的api去获取文件的MiMEType : //对该文件发送一个异步请求,拿到文件的MIMEType - (void ...

  3. 使用NSURLConnection实现大文件断点下载

    使用NSURLConnection实现大文件断点下载 由于是实现大文件的断点下载,不是下载一般图片什么的.在设计这个类的时候本身就不会考虑把下载的文件缓存到内存中,而是直接写到文件系统. 要实现断点下 ...

  4. ios开发网络学习三:NSURLConnection小文件大文件下载

    一:小文件下载 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDele ...

  5. ios开发网络学习九:NSURLSessionDownloadTask实现大文件下载

    一:NSURLSessionDownloadTask:实现文件下载:无法监听进度 #import "ViewController.h" @interface ViewControl ...

  6. ios开发网络学习十:利用文件句柄实现大文件下载

    #import "ViewController.h" @interface ViewController ()<NSURLSessionDataDelegate> @p ...

  7. iOS开发RunLoop学习:四:RunLoop的应用和RunLoop的面试题

    一:RunLoop的应用 #import "ViewController.h" @interface ViewController () /** 注释 */ @property ( ...

  8. iOS 大文件断点下载

    iOS 在下载大文件的时候,可能会因为网络或者人为等原因,使得下载中断,那么如何能够进行断点下载呢? // resumeData的文件路径 #define XMGResumeDataFile [[NS ...

  9. Retrofit 2.0 超能实践(四),完成大文件断点下载

    作者:码小白 文/CSDN 博客 本文出自:http://blog.csdn.net/sk719887916/article/details/51988507 码小白 通过前几篇系统的介绍和综合运用, ...

随机推荐

  1. 通过一个案例彻底读懂10046 trace--字节级深入破解

    转载请注明出处:http://blog.csdn.net/guoyjoe/article/details/37840583 2014.7.23晚20:30 Oracle support组猫大师分享&l ...

  2. js24---工厂模式2

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...

  3. [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.0:compile (default-compile) 问题解决

    问题描述详情: 无论你的问题是3.0还是3.1还是任何一个版本,则都可以通过以下版本来解决 解决办法: 把默认的Internal JRE改成了JAVA_HOME. 运行后成功了,截图如下:

  4. Emmet学习教程

    Emmet (前身为 Zen Coding) 是一个能大幅度提高前端开发效率的一个工具,Emmet是很成熟的并且非常适用于编写HTML/XML 和 CSS 代码的前端开发人员,但也可以用于编程语言.所 ...

  5. mobx项目创建 + mobx项目流程代码

    一. 安装mobx 1. react 安装并 reject抽离配置 1. 全局安装 create-react-app 这个脚手架 npm/cnpm i create-react-app -g yarn ...

  6. 常用处理字符串的SQL函数

    汇总函数:Count.Sum.AVG.MAX.min; 数学函数: ABS:绝对值.floor:给出比给定值小的最大整数. round(m,n):m为给定的值,n为小数点后保留的位数. power(m ...

  7. 【Educational Codeforces Round 35 A】 Nearest Minimums

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 找出最小的数字的位置. 最近的肯定是相邻的某对. [代码] #include <bits/stdc++.h> using ...

  8. 9. ZooKeeper之搭建单机模式。

    转自:https://blog.csdn.net/en_joker/article/details/78673456 在集群和单机两种模式下,我们基本完成了分别针对生产环境和开发环境ZooKeeper ...

  9. ORA-01665 control file is not a standby control file

    ORA-01665错误处理 问题描述: 在备库启动至mount状态时,报如下错误: ORA-01665: control file is not a standby control file 解决办法 ...

  10. JQuery源码解析 目录

    1. a.$查询符号就是放在沙盒里面的: window.jQuery = window.$ = jQuery; b.一个jQuery对象无 new 构造: eg: $("#text" ...