简单实现断点下载



转载地址:    浏览记录被删除,无法记得。   囧,囧,囧。  



@interface ViewController ()<NSURLSessionDelegate>


@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (weak, nonatomic) IBOutlet UIButton *startBtn;

@property (weak, nonatomic) IBOutlet UIButton *stopBtn;


@property (weak, nonatomic) IBOutlet UIProgressView *secondPV;




@property (nonatomic, strong) NSMutableDictionary *tasks;


@property (nonatomic, strong) NSOutputStream *stream; //

@property (nonatomic,assign) NSInteger fileTotalLength; // 文件总长度


@property (nonatomic,strong) NSMutableArray *urlArray; // 需要下载的URL

@property (nonatomic,strong) NSURLSession *session;



@property (nonatomic,assign) int index; // 任务标识

@property (nonatomic,strong) NSMutableArray *filePathArray; // 本地file记录


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

    

     _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

    

    _urlArray = [[NSMutableArray alloc]init];

    [_urlArray addObject:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];

    [_urlArray addObject:@"http://pic6.nipic.com/20100330/4592428_113348097000_2.jpg"];

    

    _filePathArray = [[NSMutableArray alloc]init];

    // 任务队列处理

    [self taskQueue:_urlArray];

}



// 队列处理任务

- (void)taskQueue:(NSMutableArray *)urlArray{

    for (NSString *requestUrl in urlArray) {

        NSString *filePath = [self fileCheck:requestUrl];

        [_filePathArray addObject:filePath];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestUrl]];

        [self requestHead:request path:filePath];

        // 创建一个Data任务

        NSURLSessionDataTask *task = [_session dataTaskWithRequest:request];

        // 保存任务

        [self.tasks setValue:task forKey:requestUrl];

    }

}



/**

 *  根据url获得对应的下载任务

 */

- (NSURLSessionDataTask *)getTask:(NSString *)url

{

    return (NSURLSessionDataTask *)[self.tasks valueForKey:url];

}



- (NSMutableDictionary *)tasks{

    if (!_tasks) {

        _tasks = [[NSMutableDictionary alloc]init];

    }

    return _tasks;

}



// 请求头部,设置请求的数据大小


- (void)requestHead:(NSMutableURLRequest *)request path:(NSString *)filePath{

    NSError *error;

    NSFileManager *manager = [NSFileManager defaultManager];

    NSDictionary *attDic = [manager attributesOfItemAtPath:filePath error:&error];

    

    // 通过设置 rang的值, 来处理是否已经下载完成或者还继续下载

    NSString *range = [NSString stringWithFormat:@"bytes=%zd-", [[attDic objectForKey:@"NSFileSize"] integerValue]];

    

    [request setValue:range forHTTPHeaderField:@"Range"];

}




// 文件判断


- (NSString *)fileCheck:(NSString *)taskUrl{

    NSArray *pathsArray =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true);

    NSString *filePath = [pathsArray lastObject];

    

    filePath = [filePath stringByAppendingPathComponent:[taskUrl lastPathComponent]];


    NSFileManager *fileManager = [NSFileManager defaultManager];

    bool isExists = [fileManager fileExistsAtPath:filePath];

    if (!isExists) {

        bool flag = [fileManager createFileAtPath:filePath contents:nil attributes:nil];

        if (flag) {

            NSLog(@"创建成功");

        }else{

            NSLog(@"创建失败");

        }

    }

    return filePath;

}



#pragma mark - 代理

#pragma mark NSURLSessionDataDelegate


// 接受到响应


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

    

    [_stream open];

    

    // 获取这个文件的大小

    _fileTotalLength = [response.allHeaderFields[@"Content-Length"] integerValue];

    

    // 接收这个请求,允许接收服务器的数据

    completionHandler(NSURLSessionResponseAllow);

}


/**

 * 接收到服务器返回的数据

 */

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{


    [_stream write:data.bytes maxLength:data.length];

    

    // 下载进度

    NSError *error;

    NSFileManager *manager = [NSFileManager defaultManager];

    NSDictionary *attDic = [manager attributesOfItemAtPath:[_filePathArray objectAtIndex:_index] error:&error];

    NSUInteger receivedSize = [[attDic objectForKey:@"NSFileSize"] integerValue];

    CGFloat progress = 1.0 * receivedSize / _fileTotalLength;

    NSLog(@"当前进度--%f",progress);

    

    if (_index == 0) {

        dispatch_async(dispatch_get_main_queue(), ^{

            

            _progressView.progress = progress;

            

        });

    }else if(_index == 1){

       dispatch_async(dispatch_get_main_queue(), ^{

           

           _secondPV.progress = progress;

           

       });

    }

    

    

    

}



// 请求完毕(成功|失败)

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{

    

    [_stream close];

    NSLog(@"文件下载成功");

    _index++;

    if (_filePathArray.count > _index) {

        _stream = [NSOutputStream outputStreamToFileAtPath:[_filePathArray objectAtIndex:_index] append:YES];

        NSURLSessionDataTask *task = [self getTask:[_urlArray objectAtIndex:_index]];

        [task resume];

    }

    

}


// 开始下载


- (IBAction)startAction:(id)sender {

    // 对应的文件需要对应的流处理。

    _stream = [NSOutputStream outputStreamToFileAtPath:[_filePathArray objectAtIndex:_index] append:YES];

    NSURLSessionDataTask *task = [self getTask:[_urlArray objectAtIndex:_index]];

    [task resume];

}



// 停止下载


- (IBAction)stopAction:(id)sender {

    NSURLSessionDataTask *task = [self getTask:[_urlArray objectAtIndex:_index]];

    [task suspend];

}


// 清理文件


- (IBAction)cleanAction:(id)sender {

    NSFileManager *manager = [NSFileManager defaultManager];

    bool  flag = [manager fileExistsAtPath:[_filePathArray objectAtIndex:_index]];

    if (flag) {

       bool removeFlag = [manager removeItemAtPath:[_filePathArray objectAtIndex:_index] error:nil];

        if (removeFlag) {

            NSLog(@"删除成功");

        }

    }

}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值