您的位置:首页 > 理论基础 > 计算机网络

IOS-网络(大文件下载)

2016-02-01 13:59 435 查看
一、不合理方式

//
//  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 = 0;
self.totalLength = 0;
//关闭文件
[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 = 0;
self.totalLength = 0;
//关闭文件
[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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: