NSURLSession文件下载

2017-09-11  本文已影响10人  小苗晓雪
#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>

@property (nonatomic, strong) NSURLSession             *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData                   *resumeData;

@end

@implementation ViewController

#pragma mark - 开始
- (IBAction)start:(id)sender
{
    //获取包含代理方法的网络会话:
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    
    //处理URL中含有中文的问题:stringByAddingPercentEncodingWithAllowedCharacters
    NSString * urlString = [@"http://192.168.1.34/同步异步串行并发.mp4"stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //根据网络会话和URL创建网络下载任务:
    self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:urlString]];
    //开启下载任务:
    [self.task resume];
}


#pragma mark - 暂停
- (IBAction)pause:(id)sender
{
    //暂停就是把任务挂起:
    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        
        // resumeData:已下载的数据:
        //保存resumeData到self.resumeData:
        self.resumeData = resumeData;
        
    }];
}


#pragma mark - 继续
- (IBAction)resume:(id)sender
{
    //根据保存的数据生成任务:
    //继续执行网络下载任务 , 从已经下载的网络数据之后跟随下载:
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    //继续开启任务:
    [self.task resume];
}


#pragma mark - <NSURLSessionDownloadDelegate>
//下载完成调用:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    //location tmp地址:
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    cachePath = [cachePath stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachePath] error:nil];
}

//监听下载进度:
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //bytesWritten 每次写入大小:
    //totalBytesWritten  已经下载量 Written:
    //totalBytesExpectedToWrite 总大小:
    NSLog(@"%lf",totalBytesWritten * 1.0 / totalBytesExpectedToWrite);
}

//请求完成:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"结束请求");
}

@end

愿编程让这个世界更美好

上一篇下一篇

猜你喜欢

热点阅读