1.使用步驟
1> 獲得NSURLSession對象
2> 利用NSURLSession對象創建對應的任務(Task)
3> 開始任務([task resume])
2.獲得NSURLSession對象
1> [NSURLSession sharedSession]
2> NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
3.任務類型
1> NSURLSessionDataTask
* 用途:用於非文件下載的GET\POST請求
NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];
NSURLSessionDataTask *task = [self.session dataTaskWithURL:url];
NSURLSessionDataTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
2> NSURLSessionDownloadTask
* 用途:用於文件下載(小文件、大文件)
NSURLSessionDownloadTask *task = [self.session downloadTaskWithRequest:request];
NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url];
NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
}];
#import "ViewController.h"
@interface ViewController ()
@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;
}
- (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://192.168.1.110:8080/Server/resources"];
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
{
}