源码0604-06-掌握-大文件断点下载(断点下载)
// // ViewController.m // 05-掌握-大文件下载 // // Created by xiaomage on 15/7/15. // Copyright (c) 2015年 小码哥. All rights reserved. // // 文件的存放路径(caches) #define XMGMp4File [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.mp4"] #import "ViewController.h" @interface ViewController () <NSURLSessionDataDelegate> /** 下载任务 */ @property (nonatomic, strong) NSURLSessionDataTask *task; /** session */ @property (nonatomic, strong) NSURLSession *session; /** 写文件的流对象 */ @property (nonatomic, strong) NSOutputStream *stream; /** 文件的总长度 */ @property (nonatomic, assign) NSInteger contentLength; @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:XMGMp4File append:YES]; } return _stream; } - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@", XMGMp4File); [[NSFileManager defaultManager] removeItemAtPath:XMGMp4File error:nil]; } /** * 开始下载 */ - (IBAction)start:(id)sender { // 创建一个Data任务 self.task = [self.session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]]; // 启动任务 [self.task resume]; } /** * 暂停下载 */ - (IBAction)pause:(id)sender { [self.task suspend]; } /** * 继续下载 */ - (IBAction)goOn:(id)sender { [self.task resume]; } #pragma mark - <NSURLSessionDataDelegate> /** * 1.接收到响应 */ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { // 打开流 [self.stream open]; // 获得文件的总长度 self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue]; // 接收这个请求,允许接收服务器的数据 completionHandler(NSURLSessionResponseAllow); } /** * 2.接收到服务器返回的数据(这个方法可能会被调用N次) */ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { // 写入数据 [self.stream write:data.bytes maxLength:data.length]; // 目前的下载长度 NSInteger downloadLength = [[[NSFileManager defaultManager] attributesOfItemAtPath:XMGMp4File error:nil][NSFileSize] integerValue]; // 下载进度 NSLog(@"%f", 1.0 * downloadLength / self.contentLength); } /** * 3.请求完毕(成功\失败) */ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { // 关闭流 [self.stream close]; self.stream = nil; } @end
07-掌握-大文件断点下载(离线断点)
// ViewController.m 05-掌握-大文件下载 // 所需要下载的文件的URL #define XMGFileURL @"http://120.25.226.186:32812/resources/videos/minion_01.mp4" // 文件名(沙盒中的文件名) #define XMGFilename XMGFileURL.md5String // 文件的存放路径(caches) #define XMGFileFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:XMGFilename] // 存储文件总长度的文件路径(caches) #define XMGTotalLengthFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"totalLength.xmg"] // 文件的已下载长度 #define XMGDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:XMGFileFullpath error:nil][NSFileSize] integerValue] #import "ViewController.h" #import "NSString+Hash.h" #import "UIImageView+WebCache.h" @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:XMGFileFullpath append:YES]; } return _stream; } - (NSURLSessionDataTask *)task { if (!_task) { NSInteger totalLength = [[NSDictionary dictionaryWithContentsOfFile:XMGTotalLengthFullpath][XMGFilename] integerValue]; if (totalLength && XMGDownloadLength == totalLength) { NSLog(@"----文件已经下载过了"); return nil; } // 创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]]; // 设置请求头 // Range : bytes=xxx-xxx NSString *range = [NSString stringWithFormat:@"bytes=%zd-", XMGDownloadLength]; [request setValue:range forHTTPHeaderField:@"Range"]; // 创建一个Data任务 _task = [self.session dataTaskWithRequest:request]; } return _task; } - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@", XMGFileFullpath); } /** * 开始下载 */ - (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] + XMGDownloadLength; // 存储总长度 NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:XMGTotalLengthFullpath]; if (dict == nil) dict = [NSMutableDictionary dictionary]; dict[XMGFilename] = @(self.totalLength); [dict writeToFile:XMGTotalLengthFullpath 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 * XMGDownloadLength / self.totalLength); } /** * 3.请求完毕(成功\失败) */ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { // 关闭流 [self.stream close]; self.stream = nil; // 清除任务 self.task = nil; } @end
// XMGDownloadManager.h // 05-掌握-大文件下载 #import <Foundation/Foundation.h> @interface XMGDownloadManager : NSObject + (instancetype)sharedInstance; - (void)download:(NSString *)url; @end
// XMGDownloadManager.m // 05-掌握-大文件下载 #import "XMGDownloadManager.h" @implementation XMGDownloadManager @end
08-掌握-大文件断点下载()
// ViewController.m // 05-掌握-大文件下载 // 文件的存放路径(caches) #define XMGMp4File [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.mp4"] // 文件的已下载长度 #define XMGDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:XMGMp4File error:nil][NSFileSize] integerValue] #import "ViewController.h" @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:XMGMp4File append:YES]; } return _stream; } - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@", XMGMp4File); } /** * 开始下载 */ - (IBAction)start:(id)sender { // 创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]]; // 设置请求头 // Range : bytes=xxx-xxx NSString *range = [NSString stringWithFormat:@"bytes=%zd-", XMGDownloadLength]; [request setValue:range forHTTPHeaderField:@"Range"]; // 创建一个Data任务 self.task = [self.session dataTaskWithRequest:request]; // 启动任务 [self.task resume]; } /** * 暂停下载 */ - (IBAction)pause:(id)sender { [self.task suspend]; } /** * 继续下载 */ - (IBAction)goOn:(id)sender { [self.task resume]; } #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] + XMGDownloadLength; // 接收这个请求,允许接收服务器的数据 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 * XMGDownloadLength / self.totalLength); } /** * 3.请求完毕(成功\失败) */ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { // 关闭流 [self.stream close]; self.stream = nil; } @end
本人无商业用途,仅仅是学习做个笔记,特别鸣谢小马哥,学习了IOS,另日语学习内容有需要文本和音频请关注公众号:riyuxuexishuji