断点下载

2018-03-28  本文已影响0人  海笙樾

今天做了断点下载视频或者MP3,具体实现如下

1、主要应用了NSURLSessionDownloadTask和NSURLSession并且遵循NSURLSessionDownloadDelegate

2、在沙盒目录下创建文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

    NSString *file = [NSString stringWithFormat:@"%@/%@",_fileName,_sectionName];

    NSString *cachesPath = [[paths objectAtIndex:0]stringByAppendingPathComponent:file];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:cachesPath];

if (blHave) {

}else{

if (![fileManager fileExistsAtPath:cachesPath]) {

            [fileManager createDirectoryAtPath:cachesPath withIntermediateDirectories:YES attributes:nil error:nil];

}

  }

3、初始化下载方法

@property (nonatomic, strong) NSURLSessionDownloadTask * downloadTask;

@property (nonatomic, strong) NSURLSession *session;

NSURL * url = [NSURL URLWithString:_mainUrl];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //3.创建session

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

    self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    //4.创建Task

    _downloadTask = [self.session downloadTaskWithRequest:request];

    //5.执行Task

    [_downloadTask resume];

5、实现代理

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite

{

    //1. 获得文件的下载进度

    NSLog(@"%f",1.0 * totalBytesWritten/totalBytesExpectedToWrite);

    [self.delegate progress:1.0 * totalBytesWritten/totalBytesExpectedToWrite];

}

/**

* 当恢复下载的时候调用该方法

*

* @param fileOffset    从什么地方下载

* @param expectedTotalBytes 文件的总大小

*/

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes

{

    NSLog(@"%s",__func__);

}

/**

* 当下载完成的时候调用

*

* @param location  文件的临时存储路径

*/

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location

{

NSArray * typeArray = [_mainUrl componentsSeparatedByString:@"."];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

//定义自己的文件最终位置

    NSString *file = [NSString stringWithFormat:@"%@/%@/%@.%@",_fileName,_sectionName,_sectionName,[typeArray lastObject]];

    NSString *cachesPath = [[paths objectAtIndex:0]stringByAppendingPathComponent:file];

    NSLog(@"文件的最终下载路径 %@",cachesPath);

    [[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:nil];

}

/**

* 请求结束

*/

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

{

}

6、断点下载的信息在 [_downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {

}];里的object.resumData里

可以把该对象存储在本地,下次进来时候取出该对象接着下载

downloadTask = [self.session downloadTaskWithResumeData:_resumData];

#pragma mark - 暂停下载

- (void)pauseDolo{

    __weak typeof(self) object = self;

    [_downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {

        object.resumData = resumeData;

        NSString * resuData = [NSString stringWithFormat:@"%@.Data",_fileName];

        [USERDEFALE setValue:resumeData forKey:resuData];

        object.downloadTask = nil;

    }];

}

#pragma mark - 取消下载

- (void)cancelDolo{

    NSString * resuData = [NSString stringWithFormat:@"%@.Data",_fileName];

    [USERDEFALE removeObjectForKey:resuData];

    [_downloadTask cancel];

}

上一篇下一篇

猜你喜欢

热点阅读