NSURLSession的文件下载

小文件的下载,代码示例:

 //NSURLSession的下载
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@"http://gss0.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/lvpics/w=600/sign=1350023d79899e51788e391472a5d990/b21bb051f819861810d03e4448ed2e738ad4e65f.jpg"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //回到主线程刷新界面
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageView.image = [UIImage imageWithData:data];
        });
        
    }] resume] ;

大文件的下载,代码示例:

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDataDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@property (nonatomic,strong) NSMutableData * fileData ;
@property (nonatomic,assign) NSInteger  totalSize ;
@property (nonatomic,assign) NSInteger  currentSize ;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;


@end

@implementation ViewController- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
   
    //1 确定资源路径
    NSURL *url = [NSURL URLWithString:@"http://meiye-mbs.oss-cn-shenzhen.aliyuncs.com/mbsFiles/0e3d0e4a0d5d4da5963e9e7617e8de101565841097849.mp4"];
    //2 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3 创建会话对象:线程不传,默认在子线程中处理
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //4 创建下载请求Task
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    //5 发送请求
    [dataTask resume];
}

#pragma mark - 代理方法
//1 接收到响应的时候调用
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    
    //得到本次请求的文件数据大小
    self.totalSize = response.expectedContentLength;
    
    //告诉系统应该接收数据
    completionHandler(NSURLSessionResponseAllow);
}

//2 接收到服务器返回数据的时候调用,可能会调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    //拼接数据
    [self.fileData appendData:data];
    
    //计算文件的下载进度并显示= 已经下载的数据/文件的总大小
    self.currentSize += data.length;
    CGFloat progress = 1.0 * self.currentSize / self.totalSize;
    self.progressView.progress = progress;
    NSLog(@"%f", progress);
}

//3 下载完成或者失败的时候调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

    //得到文件的名称:得到请求的响应头信息,获取响应头信息中推荐的文件名称
    NSString *fileName = [task.response suggestedFilename];
    //拼接文件的存储路径(沙盒路径Cache + 文件名)
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //下载的路径
    NSString *fullPath = [cache stringByAppendingPathComponent:fileName];

    //下载好的数据写入到磁盘
    [self.fileData writeToFile:fullPath atomically:YES];
    NSLog(@"filePath = %@", fullPath);
}


- (NSMutableData *)fileData {
    if (!_fileData) {
        _fileData = [NSMutableData data];
    }
    return _fileData;
}

如果按照上面那段代码的话,可以实现功能,但是有一个问题,就是 内存会飚升。为了处理这个问题,直接把拿到的数据,就写入沙盒,

逻辑如下:

//文件句柄(指针)NSFileHandle
/**
 特点:在写数据的时候边写数据边移动位置
 使用步骤:
 (1)创建空的文件
 (2)创建文件句柄指针指向文件
 (3)当接收到数据的时候,使用该句柄来写数据
 (4)当所有的数据写完,应该关闭句柄指针
 */

修改如下:

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDataDelegate>

@property (nonatomic,assign) NSInteger  totalSize ;
@property (nonatomic,assign) NSInteger  currentSize ;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (nonatomic,strong) NSFileHandle * handle ;


@end

@implementation ViewController


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
   
    //1 确定资源路径
    NSURL *url = [NSURL URLWithString:@"http://meiye-mbs.oss-cn-shenzhen.aliyuncs.com/mbsFiles/0e3d0e4a0d5d4da5963e9e7617e8de101565841097849.mp4"];
    //2 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3 创建会话对象:线程不传,默认在子线程中处理
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //4 创建下载请求Task
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    //5 发送请求
    [dataTask resume];
}

#pragma mark - 代理方法
//1 接收到响应的时候调用
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    
    //得到文件的名称:得到请求的响应头信息,获取响应头信息中推荐的文件名称
    NSString *fileName = [response suggestedFilename];
    //拼接文件的存储路径(沙盒路径Cache + 文件名)
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //下载的路径
    NSString *fullPath = [cache stringByAppendingPathComponent:fileName];
    
    //(1)创建空的文件
    [[NSFileManager defaultManager] createFileAtPath:fullPath contents:nil attributes:nil];
    //(2)创建文件句柄指针指向文件
     self.handle = [NSFileHandle fileHandleForWritingAtPath:fullPath];
    
    //得到本次请求的文件数据大小
    self.totalSize = response.expectedContentLength;
    
    //告诉系统应该接收数据
    completionHandler(NSURLSessionResponseAllow);
}

//2 接收到服务器返回数据的时候调用,可能会调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [self.handle writeData:data];
    
    //计算文件的下载进度并显示= 已经下载的数据/文件的总大小
    self.currentSize += data.length;
    CGFloat progress = 1.0 * self.currentSize / self.totalSize;
    self.progressView.progress = progress;
    NSLog(@"%f", progress);
}

//3 下载完成或者失败的时候调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    
    //(4)当所有的数据写完,应该关闭句柄指针
    [self.handle closeFile];
}

猜你喜欢

转载自www.cnblogs.com/lyz0925/p/11580252.html