NSURLSessionDownloadTask大文件断点下载
2016-08-07 本文已影响109人
solozyx
NSURLSessionDownloadDelegate
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
/** 下载任务 */
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@end
@implementation ViewController
/**
* 开始下载
*/
- (IBAction)start:(id)sender {
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];
self.task = [session downloadTaskWithURL:url];
[self.task resume];
}
/**
* 暂停下载
*/
- (IBAction)pause:(id)sender {
[self.task suspend];
}
/**
* 继续下载
*/
- (IBAction)goOn:(id)sender {
[self.task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
/**
* 每当写入数据到临时文件时,就会调用一次这个方法
* totalBytesExpectedToWrite:总大小
* totalBytesWritten: 已经写入的大小
* bytesWritten: 这次写入多少
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
NSLog(@"%s",__func__);
NSLog(@"%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
NSLog(@"%s",__func__);
}
/**
* 下载完毕就会调用一次这个方法
*/
- (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:(NSURLSessionDownloadTask *)task
didCompleteWithError:(NSError *)error{
NSLog(@"%s",__func__);
}
@end
// 0.996829
// -[ViewController URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:]
// 0.999656
// -[ViewController URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:]
// 1.000000
// /Users/zhaoyingxin/Library/Developer/CoreSimulator/Devices/1146129D-06F4-457B-83AC-B97F3B7ECA32/data/Containers/Data/Application/265D1E5E-A086-4338-8538-104F6D48663D/Library/Caches/minion_01.mp4
// -[ViewController URLSession:task:didCompleteWithError:]