10.6 下载&断点续传

视频转换网站:硕鼠

#import "ViewController.h"

@interface ViewController ()

{

    NSMutableData *_datas;

    NSURLSession *_session;

    NSURLSessionDataTask *_task;

    NSString *_path;

    NSString *_basePath;

    NSFileHandle *_writeHandle;

}

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    _basePath = @"/Users/apple/Desktop";
    
    _datas = [NSMutableData data];
    _path = @"http://www.3337973.cc/imgall/mjuxu2djfy2diojtfzrw63i/uploads/allimg/140828/3-140RQ34K1.jpg";
  
    _path = @"http://link.hhtjim.com/163/280761.mp3";
    
//    _path = @"http://data.vod.itc.cn/?rb=1&prot=1&key=jbZhEJhlqlUN-Wj_HEI8BjaVqKNFvDrn&prod=flash&pt=1&new=/198/232/8mIXFONKIQNHKlScaM76kB.mp4";
   
   
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];

   

    //断点续传,把Request定义为可变,这样才可以把"Range"的值传到服务器
    NSMutableURLRequest *mutiRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_path]];

   //断点续传,把bytes设置成读本地的文件大小下载了多少,然后就可以接着下载
    [mutiRequest setValue:@"bytes=1048000-" forHTTPHeaderField:@"Range"];
    
    _task = [_session dataTaskWithRequest:mutiRequest];

    

//    [_task resume];

}

//1  请求下载

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{

    NSHTTPURLResponse *resp = (NSHTTPURLResponse*)response;
    
    NSLog(@"%lld",resp.expectedContentLength);

    NSLog(@"--->%@",response);

//    断点续传,状态码要加上206

    if(resp.statusCode == 200 || resp.statusCode == 206){
    
        completionHandler(NSURLSessionResponseAllow);
    }
}

//2  下载任务

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask

    didReceiveData:(NSData *)data{

    NSLog(@"-->%ld",data.length);

     //进度条
    _myProgress.progress =(double)_currentLength/_tatalLength;

    //文字显示进度
    _dLabel.text = [NSString stringWithFormat:@"下载进度%f",(double)_currentLength/_tatalLength];    

    if(_writeHandle){
    
        [_writeHandle writeData:data];
    }
}

//3   判断错误

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

didCompleteWithError:(nullable NSError *)error{

    if(!error){
    
        NSLog(@"done");
       

        //AtPath: 剪切前的文件地址    ToPath: 剪切后的文件地址
        [[NSFileManager defaultManager]moveItemAtPath:[_basePath stringByAppendingPathComponent:[self cacheFileNameWithFile:[self fileNameWithURL:_path]]] toPath:[_basePath stringByAppendingPathComponent:[self fileNameWithURL:_path]] error:nil];
        
    }else{
    
        NSLog(@"error:%@",error);
    }
    
    [_writeHandle closeFile];
}

- (IBAction)buttonClicked:(UIButton*)sender {

    if([sender.currentTitle isEqualToString:@"开始"]){
       
        NSString *targetFilePath = [_basePath stringByAppendingPathComponent:[self cacheFileNameWithFile:[self fileNameWithURL:_path]]];
        
        if(![[NSFileManager defaultManager]fileExistsAtPath:targetFilePath isDirectory:nil]){

            //如果没有目标文件就创建一个
            [[NSFileManager defaultManager]createFileAtPath:targetFilePath contents:nil attributes:nil];
        }

        //打开NSFileHandle通道
        _writeHandle = [NSFileHandle fileHandleForWritingAtPath:targetFilePath];

        [_writeHandle seekToEndOfFile];
        
        if(_task.state == NSURLSessionTaskStateSuspended){
       
            [_task resume];
            
        }else{
        //继续下载
            _task = [_session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_path]]];

            [_task resume];
            
        }
        NSLog(@"开始");
    }
    else{//暂停
    
        if(_task.state == NSURLSessionTaskStateRunning){
        
            [_task suspend];

            NSLog(@"暂停");
        }        
    }
}

//文件名   分割/号里面内容为数组,取最后一个元素作为名字
- (NSString*)fileNameWithURL:(NSString*)urlString{
    if(!urlString){
    
        return nil;
    }

    NSArray *tempArray = [urlString componentsSeparatedByString:@"/"];
    NSString *fileName = tempArray.lastObject;

    return fileName;
}

//缓存名   用.=号分割fileName,取第一个元素做缓存名
- (NSString*)cacheFileNameWithFile:(NSString*)fileName{

    if(!fileName){
    
        return nil;
    }

    NSArray *tempArr = [fileName componentsSeparatedByString:@"."];

    NSString *tempString = tempArr.firstObject;

    return [NSString stringWithFormat:@"%@.cache",tempString];

}

@end

你可能感兴趣的:(10.6 下载&断点续传)