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(十一) scn
SCN(System Chang Number)作为oracle中的一个重要机制,在数据恢复.Data Guard.Streams复制.RAC节点间的同步等各个功能中起着重要作用. 理解SCN的运作机 ...
- 005-spring cache-配置缓存存储
一.概述 缓存抽象提供了多种存储集成.要使用它们,需要简单地声明一个适当的CacheManager - 一个控制和管理Caches的实体,可用于检索这些实体以进行存储. 1.1.基于JDK Concu ...
- java-基础-【四】实际编程中的对象
一.概述 实际编程开发中,仅仅一个数据库对象映射是满足不了各种复杂需求. O/R Mapping 是 Object Relational Mapping(对象关系映射)的缩写.通俗点讲,就是将对象与关 ...
- python模块之pyMySql
目录: 安装 使用 一.安装 本模块为python第三方模块,需要单独安装.作用为调用mysql接口执行模块 pip3 install pyMySql 二.使用 1.执行SQL #!/usr/bin/ ...
- 4.1 Routing -- Introduction
一.Routing 1. 当用户与应用程序交互时,它会经过很多状态.Ember.js为你提供了有用的工具去管理它的状态和扩展你的app. 2. 要理解为什么这是重要的,假设我们正在编写一个Web应用程 ...
- vs2010中如何编写C语言程序
File->New->Project 在打开的New Project对话框中最左侧一栏中选择Visual C++下面的CLR,之后在其右侧的区域中选择CLR Empty Applicati ...
- ng-深度学习-课程笔记-11: 卷积神经网络(Week1)
1 边缘检测( edage detection ) 下图是垂直边缘检测的例子,实际上就是用一个卷积核进行卷积的过程. 这个例子告诉我们,卷积可以完成垂直方向的边缘检测.同理卷积也可以完成水平方向的边缘 ...
- CentOS7搭建Gitlab详细过程
1.参见Gitlab官网说明 原文地址:https://about.gitlab.com/install/#centos-7 1.安装并配置必要的依赖项 在CentOS 7(和RedHat / O ...
- Broken pipe错误原因
这个异常是由于以下几个原因造成. 1.客户端再发起请求后没有等服务器端相应完,点击了stop按钮,导致服务器端接收到取消请求. 通常情况下是不会有这么无聊的用户,出现这种情况可能是由于用户提交了 ...
- DB开发之oracle
常用命令: select table_name from user_tables; //当前用户的表 select table_name from all_tables; //所有用户的表 sel ...