//
//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.創(chuàng)建一個下載任務
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 :包含了繼續(xù)下載的開始位置\下載的url
vc.resumeData= resumeData;
vc.task=nil;
}];
}
/*恢復的點擊方法**/
- (IBAction)resume:(id)sender {
//傳入上次暫停下載返回的數(shù)據(jù)东跪,就可以恢復下載
self.task= [self.sessiondownloadTaskWithResumeData:self.resumeData];
//開始任務
[self.taskresume];
//清空
self.resumeData=nil;
}
#pragma mark - NSURLSessionDownloadDelegate
/*下載完成的回調(diào)**/
- (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];
}
/*下載進度的回調(diào)**/
- (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;
}
/*恢復下載的回調(diào),從哪里開始下載**/
- (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