ios开发网络学习四:NSURLConnection大文件断点下载
#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大文件断点下载的更多相关文章
- ios开发网络学习十一:NSURLSessionDataTask离线断点下载(断点续传)
#import "ViewController.h" #define FileName @"121212.mp4" @interface ViewControl ...
- ios开发网络学习五:MiMEType ,多线程下载文件思路,文件的压缩和解压缩
一:MiMEType:一般可以再百度上搜索到相应文件的MiMEType,或是利用c语言的api去获取文件的MiMEType : //对该文件发送一个异步请求,拿到文件的MIMEType - (void ...
- 使用NSURLConnection实现大文件断点下载
使用NSURLConnection实现大文件断点下载 由于是实现大文件的断点下载,不是下载一般图片什么的.在设计这个类的时候本身就不会考虑把下载的文件缓存到内存中,而是直接写到文件系统. 要实现断点下 ...
- ios开发网络学习三:NSURLConnection小文件大文件下载
一:小文件下载 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDele ...
- ios开发网络学习九:NSURLSessionDownloadTask实现大文件下载
一:NSURLSessionDownloadTask:实现文件下载:无法监听进度 #import "ViewController.h" @interface ViewControl ...
- ios开发网络学习十:利用文件句柄实现大文件下载
#import "ViewController.h" @interface ViewController ()<NSURLSessionDataDelegate> @p ...
- iOS开发RunLoop学习:四:RunLoop的应用和RunLoop的面试题
一:RunLoop的应用 #import "ViewController.h" @interface ViewController () /** 注释 */ @property ( ...
- iOS 大文件断点下载
iOS 在下载大文件的时候,可能会因为网络或者人为等原因,使得下载中断,那么如何能够进行断点下载呢? // resumeData的文件路径 #define XMGResumeDataFile [[NS ...
- Retrofit 2.0 超能实践(四),完成大文件断点下载
作者:码小白 文/CSDN 博客 本文出自:http://blog.csdn.net/sk719887916/article/details/51988507 码小白 通过前几篇系统的介绍和综合运用, ...
随机推荐
- [Angular & Unit Testing] Testing Component with Store
When using Ngrx, we need to know how to test the component which has Router injected. Component: imp ...
- makeMtk- user 版本编译
有时候我们需要在我们的手机上编译user 版本,先说一下user 跟eng版本的区别 user:这个版本是没有root权限的,当你adb shell进入后,linux下显示的是$,不可以push ap ...
- Day2下午解题报告
预计分数:100+100+30=230 实际分数:100+100+30=230人品爆发&&智商爆发&&手感爆发 T3数据好水,,要是把数组开大一点的话还能多得10分,, ...
- Android 在滚动列表中实现视频的播放(ListView & RecyclerView)
这片文章基于开源项目: VideoPlayerManager. 所有的代码和示例都在那里.本文将跳过许多东西.因此如果你要真正理解它是如何工作的,最好下载源码,并结合源代码一起阅读本文.但是即便是没有 ...
- CISP/CISA 每日一题 17
CISSP 每日一题(答) What are often added to passwords to maketheir resultant hash secure and resistant to ...
- HDU 3232 && UVA 12230 (简单期望)
Crossing Rivers Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- 108.sqllite3(C语言数据库库)详解
//创建数据库,插入表,生效 //创建数据库,插入表,生效 void create_database() { //数据库指针 sqlite3 *db=; //打开数据数据库,初始化指针 int res ...
- python序列中是否包含某个元素
http://outofmemory.cn/code-snippet/9098/python-list-contains-with-in-not-in theList = ['a','b','c'] ...
- ThinkPHP5.0的安装
ThinkPHP5.0的安装很简单: 1.下载“phpstudy”安装 2.下载thinkphp源文件 3.把thinkphp源文件解压并放到phpstudy目录下的“WWW”目录 4.然后开启服务并 ...
- ActiveX控件开发 C#
转自:http://hi.baidu.com/charlesx_kst/item/9c2f42e2920db3f42b09a4ff 前言: 这段时间因为工作的需要,研究了一下ActiveX控件.总结如 ...