warning:邏輯不完整,可酌情參考,后面完善邏輯
<NSURLSessionDownloadDelegate>
#import "ViewController.h"
// resumeData的文件路徑
#define ZYXResumeDataFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"resumeData.tmpdata"]
@interface ViewController () <NSURLSessionDownloadDelegate>
/** 下載任務(wù) */
@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 {
// 獲得下載任務(wù)
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 {
// 一旦這個(gè)task被取消了嘴办,就無(wú)法再恢復(fù)
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
self.resumeData = resumeData;
// 可以將resumeData寫入沙盒卵贱,保存起來(lái)
// 下次進(jìn)入程序淌铐,就可以將resumeData讀取進(jìn)來(lái),繼續(xù)下載
[resumeData writeToFile:ZYXResumeDataFile atomically:YES];
}];
}
/**
* 繼續(xù)下載
*/
- (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__);
}
/**
* 每當(dāng)寫入數(shù)據(jù)到臨時(shí)文件時(shí),就會(huì)調(diào)用一次這個(gè)方法
* totalBytesExpectedToWrite:總大小
* totalBytesWritten: 已經(jīng)寫入的大小
* 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);
}
/**
* 下載完畢就會(huì)調(diào)用一次這個(gè)方法
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
// 文件存放的真實(shí)路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSLog(@"%@",file);
// 剪切l(wèi)ocation的臨時(shí)文件到真實(shí)路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionDownloadTask *)task
didCompleteWithError:(NSError *)error{
// 保存恢復(fù)數(shù)據(jù)
self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}
@end
實(shí)現(xiàn)離線斷點(diǎn)下載
//
// 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]
// 存儲(chǔ)文件總長(zhǎng)度的文件路徑(caches)
#define ZYXTotalLengthFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"totalLength.info"]
// 文件的已下載長(zhǎng)度
#define ZYXDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:ZYXFileFullpath error:nil][NSFileSize] integerValue]
@interface ViewController () <NSURLSessionDataDelegate>
/** 下載任務(wù) */
@property (nonatomic, strong) NSURLSessionDataTask *task;
/** session */
@property (nonatomic, strong) NSURLSession *session;
/** 寫文件的流對(duì)象 */
@property (nonatomic, strong) NSOutputStream *stream;
/** 文件的總長(zhǎng)度 */
@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(@"----文件已經(jīng)下載過了");
return nil;
}
// 創(chuàng)建請(qǐng)求
NSURL *url = [NSURL URLWithString:ZYXRemoteServerFileURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 設(shè)置請(qǐng)求頭
// Range : bytes=xxx-xxx
NSString *range = [NSString stringWithFormat:@"bytes=%zd-", ZYXDownloadLength];
[request setValue:range forHTTPHeaderField:@"Range"];
// 創(chuàng)建一個(gè)Data任務(wù)
_task = [self.session dataTaskWithRequest:request];
}
return _task;
}
/**
* 開始下載
*/
- (IBAction)start:(id)sender {
// 啟動(dòng)任務(wù)
[self.task resume];
}
/**
* 暫停下載
*/
- (IBAction)pause:(id)sender {
[self.task suspend];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到響應(yīng)
*/
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSHTTPURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
// 打開流
[self.stream open];
// 獲得服務(wù)器這次請(qǐng)求 返回?cái)?shù)據(jù)的總長(zhǎng)度
self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + ZYXDownloadLength;
// 存儲(chǔ)總長(zhǎng)度
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:ZYXTotalLengthFullpath];
if (dict == nil) dict = [NSMutableDictionary dictionary];
dict[ZYXFilename] = @(self.totalLength);
[dict writeToFile:ZYXTotalLengthFullpath atomically:YES];
// 接收這個(gè)請(qǐng)求,允許接收服務(wù)器的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
}
/**
* 2.接收到服務(wù)器返回的數(shù)據(jù)(這個(gè)方法可能會(huì)被調(diào)用N次)
*/
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
// 寫入數(shù)據(jù)
[self.stream write:data.bytes maxLength:data.length];
// 下載進(jìn)度
NSLog(@"%f", 1.0 * ZYXDownloadLength / self.totalLength);
}
/**
* 3.請(qǐng)求完畢(成功\失敗)
*/
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error{
// 關(guān)閉流
[self.stream close];
self.stream = nil;
// 清除任務(wù)
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