zoukankan      html  css  js  c++  java
  • NSURLSession的断点下载

    #import "ViewController.h"
    
    @interface ViewController () <NSURLSessionDownloadDelegate, NSURLSessionDataDelegate>
    @property (weak, nonatomic) IBOutlet UIProgressView *progressView;
    - (IBAction)download:(UIButton *)sender;
    
    @property (nonatomic, strong) NSURLSessionDownloadTask *task;
    @property (nonatomic, strong) NSData *resumeData;
    @property (nonatomic, strong) NSURLSession *session;
    @end
    
    @implementation ViewController
    
    - (NSURLSession *)session
    {
        if (!_session) {
            // 获得session
            NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
            self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        }
        return _session;
    }
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
    }
    
    - (IBAction)download:(UIButton *)sender {
        // 按钮状态取反
        sender.selected = !sender.isSelected;
        
        if (self.task == nil) { // 开始(继续)下载
            if (self.resumeData) { // 恢复
                [self resume];
            } else { // 开始
                [self start];
            }
        } else { // 暂停
            [self pause];
        }
    }
    
    /**
     *  从零开始
     */
    - (void)start
    {
        // 1.创建一个下载任务
        NSURL *url = [NSURL URLWithString:@"http://******************.mp4"];
        self.task = [self.session downloadTaskWithURL:url];
        
        // 2.开始任务
        [self.task resume];
    }
    
    /**
     *  恢复(继续)
     */
    - (void)resume
    {
        // 传入上次暂停下载返回的数据,就可以恢复下载
        self.task = [self.session downloadTaskWithResumeData:self.resumeData];
        
        // 开始任务
        [self.task resume];
        
        // 清空
        self.resumeData = nil;
    }
    
    /**
     *  暂停
     */
    - (void)pause
    {
        __weak typeof(self) vc = self;
        [self.task cancelByProducingResumeData:^(NSData *resumeData) {
            //  resumeData : 包含了继续下载的开始位置下载的url
            vc.resumeData = resumeData;
            vc.task = nil;
        }];
    }
    
    #pragma mark - NSURLSessionDownloadDelegate
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
    didFinishDownloadingToURL:(NSURL *)location
    {
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
        NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
        
        // 将临时文件剪切或者复制Caches文件夹
        NSFileManager *mgr = [NSFileManager defaultManager];
        
        // AtPath : 剪切前的文件路径
        // ToPath : 剪切后的文件路径
        [mgr moveItemAtPath:location.path toPath:file error:nil];
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
          didWriteData:(int64_t)bytesWritten
     totalBytesWritten:(int64_t)totalBytesWritten
    totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
    {
        NSLog(@"获得下载进度--%@", [NSThread currentThread]);
        // 获得下载进度
        self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
     didResumeAtOffset:(int64_t)fileOffset
    expectedTotalBytes:(int64_t)expectedTotalBytes
    {
        
    }
    
    //- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
    //{
    //
    //}
    //
    //- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
    //{
    //
    //}
    
    
    
    @end
  • 相关阅读:
    CF1175B Catch Overflow!
    震惊!一蒟蒻竟然写出fhqTreap
    树上差分
    洛谷 P3128 最大流Max Flow
    线段树的标记永久化/二维线段树模板
    矩阵加速~desire drive
    置换相关
    树形图们
    严格单调递增与非严格之间的转换
    记录延续性的一类dp
  • 原文地址:https://www.cnblogs.com/ZMiOS/p/5498244.html
Copyright © 2011-2022 走看看