断点下载

#import "ViewController.h"

@interface ViewController () <NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;


/**  下载任务的属性  */
@property (nonatomic, strong) NSURLSessionDownloadTask *task;

/**  网络请求类  */
@property (nonatomic, strong) NSURLSession *session;

/**  发送请求类  */
@property (nonatomic, strong) NSURLRequest *request;

/**  保存已经下载的数据,供继续下载使用  */
@property (nonatomic, strong) NSMutableData *data;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置progress的初始值
    self.progressView.progress = 0;
}


#pragma mark - 开始下载
- (IBAction)start:(id)sender {
    
    // 下载的url
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/img/bdlogo.png"];
    
    // 初始化请求类
    self.request = [NSURLRequest requestWithURL:url];
    
    // 创建NSURLSession
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    // 下载请求任务
    self.task = [self.session downloadTaskWithRequest:self.request];
    
    // 开启
    [self.task resume];
}


#pragma mark - 暂停下载
- (IBAction)pause:(id)sender {
    
    if (self.task) {
        
        __weak typeof(self)weakSelf = self;
        // 暂停并保存之前已经下载的内容
        [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            
            weakSelf.data = [NSMutableData dataWithData:resumeData];
        }];
    }
    
    // 暂停任务
    [self.task suspend];
}


#pragma mark - 继续下载
- (IBAction)continue:(id)sender {
    
    // 判断当前有没有任务,是发送请求,还是处理数据
    if (self.task != nil) {
        
        // 说明已经下载,这里要处理的就是数据
        self.task = [self.session downloadTaskWithResumeData:self.data];
    } else {
        
        // 此时没有下载任何内容,应该重新发送请求进行下载
        self.task = [self.session downloadTaskWithRequest:self.request];
    }
    
    // 启动
    [self.task resume];
}


#pragma mark - 代理方法
// 下载完成的方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    [fileManager moveItemAtPath:location.path toPath:path error:nil];
    self.imgView.image = [UIImage imageWithContentsOfFile:path];
}


- (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);
    
    // 设置progress的进度值
    self.progressView.progress = (CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;
}

@end

posted on 2016-07-25 20:46  ivonne  阅读(96)  评论(0编辑  收藏  举报

导航