iOS开发 ----- 网络请求4 ----- 下载数据以及断点续传

NSURLSession下载文件

系列导航

网络请求1 —> 概览

网络请求2 —> 请求数据

网络请求3 —> 上传数据

网络请求4 —> 下载数据以及断点续传

这个是Block方式,相当的简单

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [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];
    // Dispose of any resources that can be recreated.
}

@end

代理方式下载

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate,NSURLSessionTaskDelegate>
@property(nonatomic,strong)UIProgressView * progess;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [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];
    // Dispose of any resources that can be recreated.
}

@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];
    // Do any additional setup after loading the view, typically from a nib.
    [self creatUI];
    [self download];
}
//创建ui 
-(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];
    // Dispose of any resources that can be recreated.
}

@end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值