iOS之NSURLSessionDownloadTask下载

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate,NSURLSessionDownloadDelegate>
///显示图片的
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
///显示进度的
@property (weak, nonatomic) IBOutlet UISlider *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];
    // Do any additional setup after loading the view, typically from a nib.
    
    //
    self.progressView.value = 0;
}
#pragma mark - 开始下载
- (IBAction)startDownLoad:(id)sender {
    
    NSString *urlStr = @"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1464602004&di=2f52d829b167189d005b506a96fbd87e&src=http://imgsrc.baidu.com/forum/pic/item/b15db8a1cd11728b829819d0c8fcc3cec2fd2c6c.jpg";
    NSURL *url = [NSURL URLWithString:urlStr];
    //初始化请求
    self.request = [NSURLRequest requestWithURL:url];
    //创建NSURLSession
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//    NSURLSessionTask *task = [session dataTaskWithRequest:self.request];
    
    //下载请求任务
    self.task = [self.session downloadTaskWithRequest:self.request];
    
    //开启
    [_task resume];
    
}
#pragma mark - 暂停下载
- (IBAction)pauseDownLoad:(id)sender {
    //暂停
    if (self.task ) {
        //暂停并保存之前已经下载的内容
        __weak typeof(self)weakSelf = self;
        [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            weakSelf.data = [NSMutableData dataWithData:resumeData];
            
        }];
        
    }
    //暂停任务
    [_task suspend];
}
#pragma mark - 继续下载
- (IBAction)continueDownLoad:(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 {
    NSLog(@"%@",location);
    // 设置文件的存放目标路径
    NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    
    NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath];
    
    NSURL *fileURL = [documentsDirectoryURL URLByAppendingPathComponent:[[downloadTask.response URL] lastPathComponent]];
    //使用
    // 如果该路径下文件已经存在,就要先将其移除,在移动文件
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:[fileURL path] isDirectory:NULL]) {
        
        [fileManager removeItemAtURL:fileURL error:NULL];
        
    }
    //让documents文件也有一份下载的文件
    [fileManager moveItemAtURL:location toURL:fileURL error:NULL];
    self.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:fileURL]];
    NSLog(@"%@",fileURL);
}
//下载中
- (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);
    //设置progressView的进度值
    self.progressView.value = (CGFloat)totalBytesWritten/(CGFloat)totalBytesExpectedToWrite;
}

@end

运行结果如图:

posted @ 2016-05-30 23:24  仗剑走天下  阅读(315)  评论(0编辑  收藏  举报