NSURLSession下载文件
系列导航
网络请求1 —> 概览
网络请求2 —> 请求数据
网络请求3 —> 上传数据
网络请求4 —> 下载数据以及断点续传
这个是Block方式,相当的简单
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self download];
}
-(void)download
{
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip"]];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSFileManager * manager = [NSFileManager defaultManager];
[manager createFileAtPath:[NSString stringWithFormat:@"%@/Documents/1.zip",NSHomeDirectory()] contents:[NSData dataWithContentsOfURL:location] attributes:nil];
NSLog(@"%@",NSHomeDirectory());
}];
[task resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
代理方式下载
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate,NSURLSessionTaskDelegate>
@property(nonatomic,strong)UIProgressView * progess;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self download];
[self creatProgess];
}
-(void)creatProgess
{
self.progess = [[UIProgressView alloc]initWithFrame:CGRectMake(100, 100, 200, 100)];
self.progess.tintColor = [UIColor redColor];
self.progess.trackTintColor = [UIColor greenColor];
[self.view addSubview:self.progess];
}
-(void)download
{
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip"]];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithRequest:request];
[downloadTask resume];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSFileManager * mamager = [NSFileManager defaultManager];
[mamager createFileAtPath:[NSString stringWithFormat:@"%@/Documents/1.zip",NSHomeDirectory()] contents:[NSData dataWithContentsOfURL:location] attributes:nil];
NSLog(@"%@",NSHomeDirectory());
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"本次发送请求的数据 -> bytesSent : %lld",bytesWritten);
NSLog(@"接收到的数据 -> totalBytesWritten : %lld",totalBytesWritten);
NSLog(@"总数据 -> totalBytesExpectedToSend : %lld",totalBytesExpectedToWrite);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.progess.progress = totalBytesWritten * 1.00 / totalBytesExpectedToWrite;
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
实现断点续传
断点续传原理
实现断点续传,也就是暂停的时候,保存当前的偏移量,也就是代理方法中的totalBytesWritten,在下次启动的时候,重设偏移量,然后继续写数据即可
NSString * byteValue = [NSString stringWithFormat:@"bytes=%ld-",totalBytesWritten];
[self.request setValue:byteValue forHTTPHeaderField:@"RANGE"];
下边贴实现代码
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property(nonatomic,strong)UIButton * buttonStart;
@property(nonatomic,strong)UIButton * buttonStop;
@property(nonatomic,strong)UIProgressView * progress;
@property(nonatomic,strong)UILabel * label;
@property(nonatomic,strong)NSURLSessionDownloadTask * task;
@property(nonatomic,strong)NSMutableURLRequest * request;
@property(nonatomic,assign)NSInteger downloadByte;
@property(nonatomic,assign)NSInteger totleByte;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self creatUI];
[self download];
}
-(void)creatUI
{
self.progress = [[UIProgressView alloc]initWithFrame:CGRectMake(20, 100, [UIScreen mainScreen].bounds.size.width - 20, 100)];
self.progress.tintColor = [UIColor redColor];
self.progress.trackTintColor = [UIColor greenColor];
[self.view addSubview:self.progress];
self.buttonStart = [[UIButton alloc]initWithFrame:CGRectMake(20, 150, 100, 50)];
[self.buttonStart setTitle:@"开始" forState:UIControlStateNormal];
self.buttonStart.backgroundColor = [UIColor greenColor];
[self.buttonStart addTarget:self action:@selector(buttonStartClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.buttonStart];
self.buttonStop = [[UIButton alloc]initWithFrame:CGRectMake(250, 150, 100, 50)];
[self.buttonStop setTitle:@"暂停" forState:UIControlStateNormal];
self.buttonStop.backgroundColor = [UIColor greenColor];
[self.buttonStop addTarget:self action:@selector(buttonStopClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.buttonStop];
self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
self.label.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, 50);
self.label.font = [UIFont systemFontOfSize:20];
self.label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:self.label];
}
-(void)buttonStartClick:(UIButton *)button
{
[self.task resume];
}
-(void)buttonStopClick:(UIButton *)button
{
[self.task suspend];
NSString * byteValue = [NSString stringWithFormat:@"bytes=%ld-",self.downloadByte];
[self.request setValue:byteValue forHTTPHeaderField:@"RANGE"];
}
-(void)download
{
self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: @"http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip"]];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"backgroundDownload"] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
self.task = [session downloadTaskWithRequest:self.request];
[self.task resume];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSFileManager * manager = [NSFileManager defaultManager];
[manager createFileAtPath:[NSString stringWithFormat:@"%@/Documents/1.zip",NSHomeDirectory()] contents:[NSData dataWithContentsOfURL:location] attributes:nil];
NSLog(@"%@",NSHomeDirectory());
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"bytesWritten : %lld",bytesWritten);
NSLog(@"totalBytesWritten : %lld",totalBytesWritten);
NSLog(@"totalBytesExpectedToWrite : %lld",totalBytesExpectedToWrite);
self.downloadByte = totalBytesWritten;
self.totleByte = totalBytesExpectedToWrite;
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
self.progress.progress = totalBytesWritten * 1.00/totalBytesExpectedToWrite;
self.label.text = [NSString stringWithFormat:@"%.2f%%",self.progress.progress*100];
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end