从网上DownLoad(断点下载)

匆匆过客 提交于 2020-03-07 05:04:04

方法步骤一、storyboard布局

 

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>
///显示图片的
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
///显示进度的
@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];
    // Do any additional setup after loading the view, typically from a nib.
    self.progressView.progress = 0  ;
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 开始下载
- (IBAction)startButton:(id)sender {
    NSString *urlStr = @"http://f.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=2b7d8fd27fd98d1076810435140f9438/503d269759ee3d6d505b9ee540166d224f4ade7a.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])];
    //下载请求任务
    self.task = [self.session downloadTaskWithRequest:self.request];
    
    //开启
    [self.task resume];
    
    
}
#pragma mark - 暂停下载
- (IBAction)pauseButton:(id)sender {
    //暂停
    if (self.task) {
        //暂停并保存之前已经下载的内容
        __weak typeof(self)weakSelf = self;
        [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            weakSelf.data = [NSMutableData data];
        }];
    }
    [self.task suspend];
}
#pragma mark - 继续下载
- (IBAction)continueButton:(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];
    
    //先找到沙盒
    NSArray *urlArray = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    
    //根据沙盒路径获取Document路径
    
    NSURL *url = [urlArray objectAtIndex:0];
    NSLog(@"url=====%@",url);
    
//    response.suggestedFilename:建议使用的文件名,一般根服务端的文件名一致
    
    NSURL *saveUrl = [url URLByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    NSLog(@"sabrUrl -------%@",saveUrl);
    //location:临时文件的路径(下载好的文件)
    //AtPath:剪切前的文件路径 //ToPath:剪切后的文件路径
    [fileManager moveItemAtPath:location.path toPath:saveUrl.path error:nil];
    self.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:saveUrl]];
  
}

#pragma mark - 下载完,部分就会调用(可能被调用多次)

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    
    //下载当前段的数据
    NSLog(@"bytesWrite = %lld",bytesWritten);
    NSLog(@"totalytesWritten = %lld",totalBytesWritten);
    NSLog(@"titalBytesExpectedToWrite = %lld",totalBytesExpectedToWrite);
    
    
    
    self.progressView.progress = (CGFloat)totalBytesWritten /(CGFloat)totalBytesExpectedToWrite;
    
    
    NSLog(@"%f",self.progressView.progress);
}


@end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!