zoukankan      html  css  js  c++  java
  • 源码0603-05-掌握-大文件下载

    //  ViewController.m
    //  05-掌握-大文件下载
    #import "ViewController.h"
    @interface ViewController () <NSURLSessionDownloadDelegate>
    
    @end
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        [self download];
    }
    
    - (void)download
    {
        // 获得NSURLSession对象
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
        
        // 获得下载任务
        NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
        
        // 启动任务
        [task resume];
    }
    
    #pragma mark - <NSURLSessionDownloadDelegate>
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {
        NSLog(@"didCompleteWithError");
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
    {
        NSLog(@"didResumeAtOffset");
    }
    
    /**
     * 每当写入数据到临时文件时,就会调用一次这个方法
     * totalBytesExpectedToWrite:总大小
     * totalBytesWritten: 已经写入的大小
     * bytesWritten: 这次写入多少
     */
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
    {
        NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
    }
    
    /**
     * 
     * 下载完毕就会调用一次这个方法
     */
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
    {
        // 文件将来存放的真实路径
        NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
        
        // 剪切location的临时文件到真实路径
        NSFileManager *mgr = [NSFileManager defaultManager];
        [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    }
    
    @end

    06-掌握-大文件断点下载

    //
    //  ViewController.m
    //  05-掌握-大文件下载
    #import "ViewController.h"
    
    @interface ViewController () <NSURLSessionDownloadDelegate>
    /** 下载任务 */
    @property (nonatomic, strong) NSURLSessionDownloadTask *task;
    @end
    
    @implementation ViewController
    /**
     * 开始下载
     */
    - (IBAction)start:(id)sender {
        // 获得NSURLSession对象
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
        
        // 获得下载任务
        self.task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
        
        // 启动任务
        [self.task resume];
    }
    
    /**
     * 暂停下载
     */
    - (IBAction)pause:(id)sender {
        [self.task suspend];
    }
    
    /**
     * 继续下载
     */
    - (IBAction)goOn:(id)sender {
        [self.task resume];
    }
    
    #pragma mark - <NSURLSessionDownloadDelegate>
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {
        NSLog(@"didCompleteWithError");
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
    {
        NSLog(@"didResumeAtOffset");
    }
    
    /**
     * 每当写入数据到临时文件时,就会调用一次这个方法
     * totalBytesExpectedToWrite:总大小
     * totalBytesWritten: 已经写入的大小
     * bytesWritten: 这次写入多少
     */
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
    {
        NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
    }
    
    /**
     * 
     * 下载完毕就会调用一次这个方法
     */
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
    {
        // 文件将来存放的真实路径
        NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
        
        // 剪切location的临时文件到真实路径
        NSFileManager *mgr = [NSFileManager defaultManager];
        [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    }
    
    @end

    07-掌握-大文件断点下载

    //  ViewController.m
    //  05-掌握-大文件下载
    // resumeData的文件路径
    #define XMGResumeDataFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"resumeData.tmp"]
    
    #import "ViewController.h"
    
    @interface ViewController () <NSURLSessionDownloadDelegate>
    /** 下载任务 */
    @property (nonatomic, strong) NSURLSessionDownloadTask *task;
    /** 保存上次的下载信息 */
    @property (nonatomic, strong) NSData *resumeData;
    
    /** session */
    @property (nonatomic, strong) NSURLSession *session;
    @end
    
    @implementation ViewController
    
    - (NSURLSession *)session
    {
        if (!_session) {
            _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
        }
        return _session;
    }
    
    //- (NSData *)resumeData
    //{
    //    if (!_resumeData) {
    //        _resumeData = [NSData dataWithContentsOfFile:XMGResumeDataFile];
    //    }
    //    return _resumeData;
    //}
    
    /**
     * 开始下载
     */
    - (IBAction)start:(id)sender {
    //    if (self.resumeData) {
    //        // 获得上次的下载任务
    //        self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    //        
    //        // 将上次的临时文件放到tmp中
    //        
    //    } else {
            // 获得下载任务
            self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
    //    }
        
        // 启动任务
        [self.task resume];
    }
    
    /**
     * 暂停下载
     */
    - (IBAction)pause:(id)sender {
        // 一旦这个task被取消了,就无法再恢复
        [self.task cancelByProducingResumeData:^(NSData *resumeData) {
            self.resumeData = resumeData;
            
    //
    //        // 可以将resumeData写入沙盒,保存起来
    //        // 下次进入程序,就可以将resumeData读取进来,继续下载
    //        [resumeData writeToFile:XMGResumeDataFile atomically:YES];
    //        
    //        // caches文件夹
    //        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //        
    //        // 缓存文件
    //        NSString *tmp = NSTemporaryDirectory();
    //        NSFileManager *mgr = [NSFileManager defaultManager];
    //        NSArray *subpaths = [mgr subpathsAtPath:tmp];
    //        NSString *file = [tmp stringByAppendingPathComponent:[subpaths lastObject]];
    //        NSString *cachesTempFile = [caches stringByAppendingPathComponent:[file lastPathComponent]];
    //        [mgr moveItemAtPath:file toPath:cachesTempFile error:nil];
    //        
    //        [@{@"tempFile" : cachesTempFile} writeToFile:[caches stringByAppendingPathComponent:@"tempFile.plist"] atomically:YES];
        }];
    }
    
    /**x
     请求这个路径:http://120.25.226.186:32812/resources/videos/minion_01.mp4
     设置请求头
     Range : 1024-2000
     */
    
    /**
     * 继续下载
     */
    - (IBAction)goOn:(id)sender {
        self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    
        [self.task resume];
    }
    
    #pragma mark - <NSURLSessionDownloadDelegate>
    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {
        NSLog(@"didCompleteWithError");
        
        // 保存恢复数据
        self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
    {
        NSLog(@"didResumeAtOffset");
    }
    
    /**
     * 每当写入数据到临时文件时,就会调用一次这个方法
     * totalBytesExpectedToWrite:总大小
     * totalBytesWritten: 已经写入的大小
     * bytesWritten: 这次写入多少
     */
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
    {
        NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
    }
    
    
    /**
     * 
     * 下载完毕就会调用一次这个方法
     */
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
    {
        // 文件将来存放的真实路径
        NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
        
        // 剪切location的临时文件到真实路径
        NSFileManager *mgr = [NSFileManager defaultManager];
        [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    }
    
    @end
    本人无商业用途,仅仅是学习做个笔记,特别鸣谢小马哥,学习了IOS,另日语学习内容有需要文本和音频请关注公众号:riyuxuexishuji
  • 相关阅读:
    MAC下cocos2dx环境搭建
    eclipse混淆打包出错
    eclipseme升级
    MyEclipse 10 中增加插件
    j2me图片处理大全
    关于svn使用
    NFS相关
    BMP文件格式图解
    UDA1341TS
    OpenOCD初始化脚本(uboot)
  • 原文地址:https://www.cnblogs.com/laugh/p/6611601.html
Copyright © 2011-2022 走看看