一、不合理方式

 //
// 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-网络(大文件下载)的更多相关文章

  1. iOS网络-04-大文件下载

    大文件下载注意事项 若不对下载的文件进行转存,会造成内存消耗急剧升高,甚至耗尽内存资源,造成程序终止. 在文件下载过程中通常会出现中途停止的状况,若不做处理,就要重新开始下载,浪费流量. 大文件下载的 ...

  2. iOS开发-大文件下载与断点下载思路

    大文件下载方案一:利用NSURLConnection和它的代理方法,及NSFileHandle(iOS9后不建议使用)相关变量: @property (nonatomic,strong) NSFile ...

  3. ios网络 -- HTTP请求 and 文件下载/断点下载

    一:请求 http://www.jianshu.com/p/8a90aa6bad6b 二:下载 iOS网络--『文件下载.断点下载』的实现(一):NSURLConnection http://www. ...

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

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

  5. 网络编程---(数据请求+slider)将网络上的大文件下载到本地,并打印其进度

    网络编程---将网络上的大文件下载到本地,并打印其进度. 点击"開始传输"button.将网络上的大文件先下载下来,下载完毕后,保存到本地. UI效果图例如以下: watermar ...

  6. iOS开发——网络篇——文件下载(NSMutableData、NSFileHandle、NSOutputStream)和上传、压缩和解压(三方框架ZipArchive),请求头和请求体格式,断点续传Range

    一.小文件下载 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion ...

  7. IOS NSURLConnection(大文件下载)

    NSURL:请求地址 NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有 一个NSURL对象 请求方法.请求头.请求体 请求超时 … … NSMutableURL ...

  8. iOS网络相关知识总结

    iOS网络相关知识总结 1.关于请求NSURLRequest? 我们经常讲的GET/POST/PUT等请求是指我们要向服务器发出的NSMutableURLRequest的类型; 我们可以设置Reque ...

  9. MTNET 自用ios网络库开源

    短短两天就在https://git.oschina.net/gangwang/MTNET这里收获15个星 github 5星, 值得收藏! MTNET 自用ios网络库开源, 自用很久了,在数歀上架的 ...

  10. iOS - 网络 - NSURLSession

    1.NSURLSession基础 NSURLConnection在开发中会使用的越来越少,iOS9已经将NSURLConnection废弃,现在最低版本一般适配iOS,所以也可以使用.NSURLCon ...

随机推荐

  1. 使用google字体发生http://fonts.gstatic.com/s/ubuntu/v8/_aijTyevf54tkVDLy-dlnFtXRa8TVwTICgirnJhmVJw.woff2

    我在使用adminTLE后台模板时,有时候会有 http://fonts.gstatic.com/s/ubuntu/v8/_aijTyevf54tkVDLy-dlnFtXRa8TVwTICgirnJh ...

  2. Rancher OS

    Rancher OS 是生产规模中运行 Docker 最小,最简单的方式.RancherOS 的所有东西都作为 Docker 管理的容器.这些系统服务包括 udev 和 rsyslog.Rancher ...

  3. Scala并发编程模型AKKA

    一.并发编程模型AKKA Spark使用底层通信框架AKKA 分布式 master worker hadoop使用的是rpc 1)akka简介 写并发程序很难,AKKA解决spark这个问题. akk ...

  4. Nginx 使用总结

    一.使用 nginx 实现 灰度发布 灰度发布,现在是很多大项目的一个标配运维特性,我们可以将一个“新的版本代码”发布到集群中的少数几台(组)机器上,以便引入线上少量真实用 户进行测试,用于验证产品改 ...

  5. 数据块加密模式以及IV的意思

    (本文资料主要来自:http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation) 目前流行的加密和数字认证算法,都是采用块加密(block ...

  6. VS Code 终端窗口无法输入命令的解决方案

    问题 今天打开vs code,打开终端窗口,发现不能输入命令了 解决方法 邮件桌面 vscode的快捷键,打开“兼容性”标签,勾选"以管理员身份运行此程序" 结果 修改之后重启vs ...

  7. Python中被双下划线包围的魔法方法

    基本的魔法方法 __new__(cls[, ...]) 用来创建对象 1. __new__ 是在一个对象实例化的时候所调用的第一个方法 2. 它的第一个参数是这个类,其他的参数是用来直接传递给 __i ...

  8. cocos代码研究(12)UI之Widget学习笔记

    理论基础 Widget类,所有UI控件的基类. 这类继承自ProtectedNode和LayoutParameterProtocol. 如果你想实现自己的UI控件,你应该继承这个类. 被 VideoP ...

  9. Bootstrap fileinput v3.0(ssm版)

    说明在上一个版本即Bootstrap fileinput v2.0(ssm版)的基础上,增加了多处都需要上传的需求 核心代码ArticleController.java package com.isd ...

  10. this指向 - Node环境

    1.全局上下文中 this /* 1.全局上下文中的 this node环境下: 严格模式下: {} {} 报错 非严格模式下:{} {} {} */ 'use strict'; // 严格模式 // ...