//
//ViewController.m
//CocoTest_1
//
//Created by S u p e r m a n on 2017/3/14.
//Copyright © 2017年张浩. All rights reserved.
//
#import"ViewController.h"
@interfaceViewController()
@property(weak,nonatomic)IBOutletUIProgressView*progressView;
/*下载文件的工具**/
@property(nonatomic,strong)NSURLSessionDownloadTask*task;
@property(nonatomic,strong)NSData*resumeData;
@property(nonatomic,strong)NSURLSession*session;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark - set/get方法
- (NSURLSession*)session {
if(_session==nil) {
NSURLSessionConfiguration* config = [NSURLSessionConfigurationdefaultSessionConfiguration];
_session= [NSURLSessionsessionWithConfiguration:configdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
}
return_session;
}
/*开始下载的方法**/
- (IBAction)downLoad:(id)sender {
// 1.创建一个下载任务
NSURL*url = [NSURLURLWithString:@"http://weixue.steptowin.com:8000/data/img/20160411/veuyytthy4b2_320_200.jpg"];
self.task= [self.sessiondownloadTaskWithURL:url];
// 2.开始任务
[self.taskresume];
}
/*暂停的点击方法**/
- (IBAction)pause:(id)sender {
__weaktypeof(self) vc =self;
[self.taskcancelByProducingResumeData:^(NSData*resumeData) {
//resumeData :包含了继续下载的开始位置\下载的url
vc.resumeData= resumeData;
vc.task=nil;
}];
}
/*恢复的点击方法**/
- (IBAction)resume:(id)sender {
//传入上次暂停下载返回的数据,就可以恢复下载
self.task= [self.sessiondownloadTaskWithResumeData:self.resumeData];
//开始任务
[self.taskresume];
//清空
self.resumeData=nil;
}
#pragma mark - NSURLSessionDownloadDelegate
/*下载完成的回调**/
- (void)URLSession:(NSURLSession*)session
downloadTask:(NSURLSessionDownloadTask*)downloadTask
didFinishDownloadingToURL:(NSURL*)location {
NSString*caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)lastObject];
// response.suggestedFilename:建议使用的文件名,一般跟服务器端的文件名一致
NSString*file = [cachesstringByAppendingPathComponent:downloadTask.response.suggestedFilename];
//将临时文件剪切或者复制Caches文件夹
NSFileManager*mgr = [NSFileManagerdefaultManager];
// AtPath :剪切前的文件路径
// ToPath :剪切后的文件路径
[mgrmoveItemAtPath:location.pathtoPath:fileerror:nil];
}
/*下载进度的回调**/
- (void)URLSession:(NSURLSession*)session
downloadTask:(NSURLSessionDownloadTask*)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
NSLog(@"获得下载进度--%@", [NSThreadcurrentThread]);
//获得下载进度
self.progressView.progress= (double)totalBytesWritten / totalBytesExpectedToWrite;
}
/*恢复下载的回调,从哪里开始下载**/
- (void)URLSession:(NSURLSession*)session
downloadTask:(NSURLSessionDownloadTask*)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
NSLog(@"fileOffset = %lld",fileOffset);
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end