#import "ViewController.h"
@interface ViewController ()<NSURLSessionDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - set/get 方法
- (NSURLSession *)session {
if (_session == nil) {
NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
- (IBAction)downLoad:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://weixue.steptowin.com:8000/data/img/20160411/veuyytthy4b2_320_200.jpg"];
self.task = [self.session downloadTaskWithURL:url];
[self.task resume];
}
- (IBAction)pause:(id)sender {
__weak typeof(self) vc = self;
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
vc.resumeData = resumeData;
vc.task = nil;
}];
}
- (IBAction)resume:(id)sender {
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
[self.task resume];
self.resumeData = nil;
}
#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil];
}
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
NSLog(@"获得下载进度--%@", [NSThread currentThread]);
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 {
[super didReceiveMemoryWarning];
}
@end