IOS-网络(大文件下载)
一、不合理方式
//
// 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 = ;
self.totalLength = ;
//关闭文件
[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 = ;
self.totalLength = ;
//关闭文件
[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
IOS-网络(大文件下载)的更多相关文章
- iOS网络-04-大文件下载
大文件下载注意事项 若不对下载的文件进行转存,会造成内存消耗急剧升高,甚至耗尽内存资源,造成程序终止. 在文件下载过程中通常会出现中途停止的状况,若不做处理,就要重新开始下载,浪费流量. 大文件下载的 ...
- iOS开发-大文件下载与断点下载思路
大文件下载方案一:利用NSURLConnection和它的代理方法,及NSFileHandle(iOS9后不建议使用)相关变量: @property (nonatomic,strong) NSFile ...
- ios网络 -- HTTP请求 and 文件下载/断点下载
一:请求 http://www.jianshu.com/p/8a90aa6bad6b 二:下载 iOS网络--『文件下载.断点下载』的实现(一):NSURLConnection http://www. ...
- ios开发网络学习三:NSURLConnection小文件大文件下载
一:小文件下载 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDele ...
- 网络编程---(数据请求+slider)将网络上的大文件下载到本地,并打印其进度
网络编程---将网络上的大文件下载到本地,并打印其进度. 点击"開始传输"button.将网络上的大文件先下载下来,下载完毕后,保存到本地. UI效果图例如以下: watermar ...
- iOS开发——网络篇——文件下载(NSMutableData、NSFileHandle、NSOutputStream)和上传、压缩和解压(三方框架ZipArchive),请求头和请求体格式,断点续传Range
一.小文件下载 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion ...
- IOS NSURLConnection(大文件下载)
NSURL:请求地址 NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有 一个NSURL对象 请求方法.请求头.请求体 请求超时 … … NSMutableURL ...
- iOS网络相关知识总结
iOS网络相关知识总结 1.关于请求NSURLRequest? 我们经常讲的GET/POST/PUT等请求是指我们要向服务器发出的NSMutableURLRequest的类型; 我们可以设置Reque ...
- MTNET 自用ios网络库开源
短短两天就在https://git.oschina.net/gangwang/MTNET这里收获15个星 github 5星, 值得收藏! MTNET 自用ios网络库开源, 自用很久了,在数歀上架的 ...
- iOS - 网络 - NSURLSession
1.NSURLSession基础 NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃,现在最低版本一般适配iOS,所以也可以使用.NSURLCon ...
随机推荐
- Oracle安装部署之 timesten install on redhat6.5
一.安装前检查 [root@localhost ~]# cat /etc/redhat-release Red Hat Enterprise Linux Server release 6.5 (San ...
- 【apt install】Unable to locate package python3-pip
解决办法: 先 sudo apt update 然后再 sudo apt install python3-pip,完成. 如果还不行的话参考这个:
- Python开发【Django】:Model操作(一)
Django ORM基本配置 到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞: 创建数据库,设计表结构和字段 使用 MySQLdb 来连接数据库,并编写数据访问层代码 业务逻辑层去 ...
- android GridView的setOnItemClickListener事件不执行
问题可能1: item设置的可能是button,或者可以click点击事件控件,导致控件执行而item按钮不执行 解决方法:设置控件 的 android:clickable="false& ...
- ffmpeg应用笔记
官网 http://ffmpeg.org/ 应用手册 http://ffmpeg.org/documentation.html 雷霄骅专栏 https://blog.csdn.net/leixiaoh ...
- Spark 参数配置的几种方法
1.Spark 属性Spark应用程序的运行是通过外部参数来控制的,参数的设置正确与否,好与坏会直接影响应用程序的性能,也就影响我们整个集群的性能.参数控制有以下方式:(1)直接设置在SparkCon ...
- mysql主从复制,及扩展
一.MySQL简单复制相关概念: 1. mysql复制的意义:Mysql复制是使得mysql完成高性能应用的前提 2. mysql复制的机制: SLAVE端线程: IO thread: 向主服务请求二 ...
- maven-eclipse 中index.html页面乱码
maven-eclipse 中index.html页面乱码: pox.xml修改: <project> -- <properties> <argLine>-Dfil ...
- 关于c语言struct和typedef
C++中使用: struct test{ int x, y;};就可以定义一个名为 test的结构体,但C中很可能编译通不过.C语言并不支持在struct后使用标示符定义结构体的名字,test将 ...
- Linux系统——公网定制化yum仓库部署
1)搭建公网源yum仓库 安装wget aliyun源 # wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel ...