NSURLSession 是 iOS 上強大的網路會話類,使用時大致分為三個步驟:
1> 取得 NSURLSession 物件 2> 透過該物件建立對應的任務(Task) 3> 啟動任務([task resume])
取得 NSURLSession 物件的兩種常見寫法:
// 方式一:單例 [NSURLSession sharedSession] // 方式二:自訂組態 NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration]; self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
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) {
}];
斷點續傳的核心思路是:暫停下載時,系統會回傳一段 resumeData,裡面記錄了已下載的位置與來源網址;恢復下載時只要把這段資料重新交給系統即可。
#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 // 懶加載 session - (NSURLSession *)session { if (!_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 { NSURL *url = [NSURL URLWithString:@"https://192.168.1.110:8080/Server/resources"]; self.task = [self.session downloadTaskWithURL:url]; [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]; // suggestedFilename:建議使用的檔名,通常與伺服器端一致 NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager *mgr = [NSFileManager defaultManager]; // 將暫存檔搬移到 Caches 目錄 [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 { // 更新下載進度 self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { } @end
透過 cancelByProducingResumeData 取得續傳資料、再以 downloadTaskWithResumeData 恢復,就能實現流暢的斷點續傳體驗,即使 App 被中斷也能從上次的位置繼續下載。