NSURLSessionDownloadTask

#import "ViewController.h"

@interface ViewController () <NSURLSessionDownloadDelegate>

@end


@implementation ViewController

- (void)download{
    // 获得NSURLSession对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                          delegate:self
                                                     delegateQueue:[[NSOperationQueue alloc] init]];
    // 获得下载任务
    NSString *urlString = @"http://www.example.com:8080/resources/videos/minion_01.mp4";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
    // 启动任务
    [task resume];
}

#pragma mark - <NSURLSessionDownloadDelegate>

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
    NSLog(@"%s",__func__);
}

/**
 * 每当写入数据到临时文件时,就会调用一次这个方法
 * 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];
    NSLog(@"%@",file);
    
    // 剪切location的临时文件到真实路径
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error{
    NSLog(@"%s",__func__);
}


// 0.000604
// 0.001548
// 0.002808
// 0.003280
// 0.999315
// 0.999787
// 1.000000
// /Users/zhaoyingxin/Library/Developer/CoreSimulator/Devices/1146129D-06F4-457B-83AC-B97F3B7ECA32/data/Containers/Data/Application/30163B0A-635F-4D01-811D-74968D3C7333/Library/Caches/minion_01.mp4
// -[ViewController URLSession:task:didCompleteWithError:]


@end


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 人类的三大动力:自恋、性、攻击性。如果远离这些动力,会死气沉沉,缺乏生命力。所以自恋是必不可少的。 自恋在某种程度...
    小笨鱼王月阅读 1,508评论 0 0
  • 朝阳初升,孕育着光和热,充满了温暖和希望,我们迎着朝阳,迈出了矫健的步伐…… 一行几人,志同道合,自由自在,快乐徒...
    冀州徒步阅读 1,513评论 0 0
  • 01 发源于长江黄河,沉淀了五千余年,中华文化源远流长、博大精深。 生在中国,长在中国,受中华文化浸染已久,但被问...
    亚历山小小阅读 3,459评论 3 7

友情链接更多精彩内容