NSURLSessionDownloadDelegate
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
/** 下載任務(wù) */
@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];
}
/**
* 繼續(xù)下載
*/
- (IBAction)goOn:(id)sender {
[self.task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
/**
* 每當(dāng)寫入數(shù)據(jù)到臨時文件時,就會調(diào)用一次這個方法
* totalBytesExpectedToWrite:總大小
* totalBytesWritten: 已經(jīng)寫入的大小
* 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__);
}
/**
* 下載完畢就會調(diào)用一次這個方法
*/
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
// 文件將來存放的真實(shí)路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSLog(@"%@",file);
// 剪切l(wèi)ocation的臨時文件到真實(shí)路徑
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:]