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 ...
随机推荐
- Linux squid 缓存服务器
一.简介 代理服务器英文全称是Proxy Server,其功能就是代理网络用户去取得网络信息. Squid是一个缓存Internet 数据的软件,其接收用户的下载申请,并自动处理所下载的数据.当一个用 ...
- Python开发【模块】:matplotlib 绘制折线图
matplotlib 1.安装matplotlib ① linux系统安装 # 安装matplotlib模块 $ sudo apt-get install python3-matplotlib # 如 ...
- 第1章 1.10计算机网络概述--OSI参考模型和TCP_IP协议
传输层负责将大数据文件分段,变成数据段. 网络层负责为小分段加上IP地址,变成数据包. 数据链路层负责将数包加上MAC地址和校验值,变成数据帧. TCP/IP协议是一群协议.不只是2个协议.
- shell export 命令
export 命令作用是 把变量导出 也可以用export来定义环境变量 导入 定义的变量 这样的话类似于python面向对象的self.变量 一样 在脚本到处调用这个变量
- Worst Performing Queries
WITH TMP AS ( SELECT TOP 100 CAST(SUM(s.total_elapsed_time) / 1000000.0 AS DECIMAL(10, 2)) AS [Total ...
- Hadoop MapReduce Task的进程模型与Spark Task的线程模型
Hadoop的MapReduce的Map Task和Reduce Task都是进程级别的:而Spark Task则是基于线程模型的. 多进程模型和多线程模型 所谓的多进程模型和多线程模型,指的是同一个 ...
- 前端基础(html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- NodeJS学习笔记三
map map对象是一个简单的键/值映射.任何值(包括对象和原始值)都可以用作一个键或一个值. var m = new Map(); var o = {p: "Hello World&quo ...
- 在Java中关于二进制、八进制、十六进制的辨析
八进制数中不可能出7以上的阿拉伯数字.但如果这个数是123.是567,或12345670,那么它是八进制数还是10进制数?单从数字的角度来讲都有可能! 八进制 所以在Java中规定,一个数如果要指明它 ...
- 2017ACM/ICPC Guangxi Invitational Solution
A: A Math Problem 题意:给出一个n,找出有多少个k满足kk <= n 思路: kk的增长很快,当k == 16 的时候就已经超过1e18 了,对于每一次询问,暴力一下就可以 ...