warning:逻辑不完整,可酌情参考,后面完善逻辑
<NSURLSessionDownloadDelegate>
#import "ViewController.h"
// resumeData的文件路径
#define ZYXResumeDataFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"resumeData.tmpdata"]
@interface ViewController () <NSURLSessionDownloadDelegate>
/** 下载任务 */
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
/** 保存上次的下载信息 */
@property (nonatomic, strong) NSData *resumeData;
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end
@implementation ViewController
- (NSURLSession *)session{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:self
delegateQueue:[[NSOperationQueue alloc] init]];
}
return _session;
}
- (NSData *)resumeData{
if (!_resumeData) {
_resumeData = [NSData dataWithContentsOfFile:ZYXResumeDataFile];
}
return _resumeData;
}
/**
* 开始下载
*/
- (IBAction)start:(id)sender {
// 获得下载任务
NSString *urlString = @"http://www.example.com:8080/resources/videos/minion_01.mp4";
NSURL *url = [NSURL URLWithString:urlString];
self.task = [self.session downloadTaskWithURL:url];
[self.task resume];
}
/**
* 暂停下载
*/
- (IBAction)pause:(id)sender {
// 一旦这个task被取消了,就无法再恢复
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
self.resumeData = resumeData;
// 可以将resumeData写入沙盒,保存起来
// 下次进入程序,就可以将resumeData读取进来,继续下载
[resumeData writeToFile:ZYXResumeDataFile atomically:YES];
}];
}
/**
* 继续下载
*/
- (IBAction)goOn:(id)sender {
self.task = [self.session downloadTaskWithResumeData:self.resumeData];
[self.task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
NSLog(@"%s",__func__);
}
/**
* 每当写入数据到临时文件时,就会调用一次这个方法
* totalBytesExpectedToWrite:总大小
* totalBytesWritten: 已经写入的大小
* bytesWritten: 这次写入多少
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
NSLog(@"%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
/**
* 下载完毕就会调用一次这个方法
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
// 文件存放的真实路径
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSLog(@"%@",file);
// 剪切location的临时文件到真实路径
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionDownloadTask *)task
didCompleteWithError:(NSError *)error{
// 保存恢复数据
self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}
@end
实现离线断点下载
//
// ViewController.m
// 05-掌握-大文件下载
// Created by xiaomage on 15/7/15.
//
#import "ViewController.h"
#import "NSString+Hash.h"
#import "UIImageView+WebCache.h"
// 所需要下载的文件的URL
#define ZYXRemoteServerFileURL @"http://120.25.226.186:32812/resources/videos/minion_02.mp4"
// 文件名(沙盒中的文件名)
#define ZYXFilename ZYXRemoteServerFileURL.md5String
// 文件的存放路径(caches)
#define ZYXFileFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:ZYXFilename]
// 存储文件总长度的文件路径(caches)
#define ZYXTotalLengthFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"totalLength.info"]
// 文件的已下载长度
#define ZYXDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:ZYXFileFullpath error:nil][NSFileSize] integerValue]
@interface ViewController () <NSURLSessionDataDelegate>
/** 下载任务 */
@property (nonatomic, strong) NSURLSessionDataTask *task;
/** session */
@property (nonatomic, strong) NSURLSession *session;
/** 写文件的流对象 */
@property (nonatomic, strong) NSOutputStream *stream;
/** 文件的总长度 */
@property (nonatomic, assign) NSInteger totalLength;
@end
@implementation ViewController
- (NSURLSession *)session{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:self
delegateQueue:[[NSOperationQueue alloc] init]];
}
return _session;
}
- (NSOutputStream *)stream{
if (!_stream) {
_stream = [NSOutputStream outputStreamToFileAtPath:ZYXFileFullpath append:YES];
}
return _stream;
}
- (NSURLSessionDataTask *)task{
if (!_task) {
NSInteger totalLength = [[NSDictionary dictionaryWithContentsOfFile:ZYXTotalLengthFullpath][ZYXFilename] integerValue];
if (totalLength && ZYXDownloadLength == totalLength) {
NSLog(@"----文件已经下载过了");
return nil;
}
// 创建请求
NSURL *url = [NSURL URLWithString:ZYXRemoteServerFileURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 设置请求头
// Range : bytes=xxx-xxx
NSString *range = [NSString stringWithFormat:@"bytes=%zd-", ZYXDownloadLength];
[request setValue:range forHTTPHeaderField:@"Range"];
// 创建一个Data任务
_task = [self.session dataTaskWithRequest:request];
}
return _task;
}
/**
* 开始下载
*/
- (IBAction)start:(id)sender {
// 启动任务
[self.task resume];
}
/**
* 暂停下载
*/
- (IBAction)pause:(id)sender {
[self.task suspend];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到响应
*/
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSHTTPURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
// 打开流
[self.stream open];
// 获得服务器这次请求 返回数据的总长度
self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + ZYXDownloadLength;
// 存储总长度
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:ZYXTotalLengthFullpath];
if (dict == nil) dict = [NSMutableDictionary dictionary];
dict[ZYXFilename] = @(self.totalLength);
[dict writeToFile:ZYXTotalLengthFullpath atomically:YES];
// 接收这个请求,允许接收服务器的数据
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服务器返回的数据(这个方法可能会被调用N次)
*/
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
// 写入数据
[self.stream write:data.bytes maxLength:data.length];
// 下载进度
NSLog(@"%f", 1.0 * ZYXDownloadLength / self.totalLength);
}
/**
* 3.请求完毕(成功\失败)
*/
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error{
// 关闭流
[self.stream close];
self.stream = nil;
// 清除任务
self.task = nil;
}
- (void)viewDidLoad{
[super viewDidLoad];
NSLog(@"%@", ZYXFileFullpath);
// /Users/admin/Library/Developer/CoreSimulator/Devices/95A0E48B-2AF9-45A0-83AE-6C065C293B5E/data/Containers/Data/Application/FCBA4453-906F-41BC-BE1C-094DF443D45F/Library/Caches/5b865634ad2abfa49e9ce097e87a8027
}
@end
网友评论