您的位置:首页 > 其它

NSURLSessionDownloadTask(下载任务)

2016-06-05 23:42 369 查看
#import "ViewController.h"
//宏定义继续任务的plist文件路径
#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 {

//构建URL
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) {

//取消当前任务,通过创建resumeData数据
[_downLoadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {

//将数据写入到plist文件中,方便下次读取
//plist文件中的信息:下载链接,已下载的数据大小,已下载的临时文件文件名
[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];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: