#import "ViewController.h"
#define kResumeDataPath [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/resumeData.plist"]
@interface ViewController () <NSURLSessionDownloadDelegate>
{
NSURLSession *_session;
NSURLSessionDownloadTask *_downLoadTask;
}
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
@implementation ViewController
#
- (void)viewDidLoad {
[super viewDidLoad];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
实现代理方法
#pragma mark NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
CGFloat progress = (CGFloat)totalBytesWritten / totalBytesExpectedToWrite;
_progressView.progress = progress;
_progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress * 100];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSString *targetPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/菊花台.mp3"];
NSFileManager *manager = [NSFileManager defaultManager];
[manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:targetPath] error:nil];
}
开始下载
- (IBAction)startDownLoad:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://218.76.27.57:8080/chinaschool_rs02/135275/153903/160861/160867/1370744550357.mp3"];
_downLoadTask = [_session downloadTaskWithURL:url];
[_downLoadTask resume];
}
暂停下载
- (IBAction)pauseDownLoad:(id)sender {
if (_downLoadTask && _downLoadTask.state == NSURLSessionTaskStateRunning) {
[_downLoadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
[resumeData writeToFile:kResumeDataPath atomically:YES];
}];
_downLoadTask = nil;
}
}
继续任务
- (IBAction)resumeDownLoad:(id)sender {
NSData *data = [NSData dataWithContentsOfFile:kResumeDataPath];
if (data) {
_downLoadTask = [_session downloadTaskWithResumeData:data];
[_downLoadTask resume];
[[NSFileManager defaultManager] removeItemAtPath:kResumeDataPath error:nil];
}
}