文件下载(断点续传)——dataTask

来源:互联网 发布:淘宝2015年销售额 编辑:程序博客网 时间:2024/06/15 07:36
<pre name="code" class="objc">// 文件的存放路径(caches)#define FilePath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.mp4"]// 文件的已下载长度#define DownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:FilePath 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:FilePath append:YES];    }    return _stream;}/** * 开始下载 */- (IBAction)start:(id)sender {    // 创建请求    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];   // 断点续传的本质是根据之前下载的进度,设置请求头。告诉服务器从哪里继续下载// Range : bytes=0-1024 表示从第0个字节下载1024个字节    bytes=2048-表示从第2048个字节下载完    // 设置请求头    NSString *range = [NSString stringWithFormat:@"bytes=%zd-", DownloadLength];    [request setValue:range forHTTPHeaderField:@"Range"];        // 创建一个Data任务// 不用downloadTask 是因为downloadTask默认把下载的文件保存在temp文件中,应用一死就被清理掉了    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];        // 获得服务器这次请求 返回数据的总长度   @"Content-Length"固定key,不能写错    self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + DownloadLength;        // 接收这个请求,允许接收服务器的数据    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 * DownloadLength / self.totalLength);}/** * 3.请求完毕(成功\失败) */- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{    // 关闭流    [self.stream close];    self.stream = nil;}@end


                                             
0 0
原创粉丝点击