斷點續傳下載是指客戶端在從網絡上下載資源時,由于某種原因中斷下載。再次開啟下載時可以從已下載完成的部分開始繼續下載未完成的部分,從而節省時間和流量。
流程說明
在手機端使用App下載視頻時,下載期間如果從Wifi模式切換到移動網絡,App默認會中斷下載。開啟斷點續傳下載后,當您從移動網絡再次切換到Wifi模式時,即可從上一次中斷的位置繼續下載。
執行斷點續傳下載操作時,效果圖如下所示。
斷點續傳下載流程如下所示。
功能說明
HTTP1.1中新增了Range頭的支持,用于指定獲取數據的范圍。Range的格式分為以下幾種。
數據范圍
說明
Range: bytes=100-
從101字節之后開始傳輸,直到傳輸到最后一個字節。
Range: bytes=100-200
從101字節開始傳輸,到201字節結束。通常用于較大的文件分片傳輸,例如視頻傳輸。
Range: bytes=-100
傳輸倒數100字節的內容,不是從0開始的100字節。
Range: bytes=0-100, 200-300
同時指定多個范圍的內容。
斷點續傳下載時需要使用
If-Match
頭來驗證服務器上的文件是否發生變化,If-Match
對應的是ETag
的值。客戶端發起請求時在Header中攜帶
Range
、If-Match
,OSS Server收到請求后會驗證If-Match中的ETag值。如果不匹配,則返回412 precondition狀態碼。OSS Server針對GetObject目前已支持
Range
、If-Match
、If-None-Match
、If-Modified-Since
、If-Unmodified-Since
,因此您可以在移動端實踐OSS資源的斷點續傳下載功能。
示例代碼
OSS iOS SDK不支持斷點續傳下載。以下代碼僅供參考了解下載流程,不建議在生產項目中使用。如需下載,可自行實現或使用第三方開源的下載框架。
iOS斷點續傳下載示例代碼如下:
#import "DownloadService.h"
#import "OSSTestMacros.h"
@implementation DownloadRequest
@end
@implementation Checkpoint
- (instancetype)copyWithZone:(NSZone *)zone {
Checkpoint *other = [[[self class] allocWithZone:zone] init];
other.etag = self.etag;
other.totalExpectedLength = self.totalExpectedLength;
return other;
}
@end
@interface DownloadService()<NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@property (nonatomic, strong) NSURLSession *session; // 網絡會話。
@property (nonatomic, strong) NSURLSessionDataTask *dataTask; // 數據請求任務。
@property (nonatomic, copy) DownloadFailureBlock failure; // 請求出錯。
@property (nonatomic, copy) DownloadSuccessBlock success; // 請求成功。
@property (nonatomic, copy) DownloadProgressBlock progress; // 下載進度。
@property (nonatomic, copy) Checkpoint *checkpoint; // 檢查節點。
@property (nonatomic, copy) NSString *requestURLString; // 文件資源地址,用于下載請求。
@property (nonatomic, copy) NSString *headURLString; // 文件資源地址,用于head請求。
@property (nonatomic, copy) NSString *targetPath; // 文件存儲路徑。
@property (nonatomic, assign) unsigned long long totalReceivedContentLength; // 已下載文件大小。
@property (nonatomic, strong) dispatch_semaphore_t semaphore;
@end
@implementation DownloadService
- (instancetype)init
{
self = [super init];
if (self) {
NSURLSessionConfiguration *conf = [NSURLSessionConfiguration defaultSessionConfiguration];
conf.timeoutIntervalForRequest = 15;
NSOperationQueue *processQueue = [NSOperationQueue new];
_session = [NSURLSession sessionWithConfiguration:conf delegate:self delegateQueue:processQueue];
_semaphore = dispatch_semaphore_create(0);
_checkpoint = [[Checkpoint alloc] init];
}
return self;
}
// DownloadRequest是下載邏輯的核心。
+ (instancetype)downloadServiceWithRequest:(DownloadRequest *)request {
DownloadService *service = [[DownloadService alloc] init];
if (service) {
service.failure = request.failure;
service.success = request.success;
service.requestURLString = request.sourceURLString;
service.headURLString = request.headURLString;
service.targetPath = request.downloadFilePath;
service.progress = request.downloadProgress;
if (request.checkpoint) {
service.checkpoint = request.checkpoint;
}
}
return service;
}
/**
* 通過Head方法獲取文件信息。OSS將文件的ETag和本地checkpoint中保存的ETag進行對比,并返回對比結果。
*/
- (BOOL)getFileInfo {
__block BOOL resumable = NO;
NSURL *url = [NSURL URLWithString:self.headURLString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"HEAD"];
// 處理Object相關信息,例如ETag用于斷點續傳時進行預檢查,content-length用于計算下載進度。
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"獲取文件meta信息失敗,error : %@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSString *etag = [httpResponse.allHeaderFields objectForKey:@"Etag"];
if ([self.checkpoint.etag isEqualToString:etag]) {
resumable = YES;
} else {
resumable = NO;
}
}
dispatch_semaphore_signal(self.semaphore);
}];
[task resume];
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
return resumable;
}
/**
* 獲取本地文件的大小。
*/
- (unsigned long long)fileSizeAtPath:(NSString *)filePath {
unsigned long long fileSize = 0;
NSFileManager *dfm = [NSFileManager defaultManager];
if ([dfm fileExistsAtPath:filePath]) {
NSError *error = nil;
NSDictionary *attributes = [dfm attributesOfItemAtPath:filePath error:&error];
if (!error && attributes) {
fileSize = attributes.fileSize;
} else if (error) {
NSLog(@"error: %@", error);
}
}
return fileSize;
}
- (void)resume {
NSURL *url = [NSURL URLWithString:self.requestURLString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"GET"];
BOOL resumable = [self getFileInfo]; // 如果resumable返回NO,表明不滿足斷點續傳的條件。
if (resumable) {
self.totalReceivedContentLength = [self fileSizeAtPath:self.targetPath];
NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", self.totalReceivedContentLength];
[request setValue:requestRange forHTTPHeaderField:@"Range"];
} else {
self.totalReceivedContentLength = 0;
}
if (self.totalReceivedContentLength == 0) {
[[NSFileManager defaultManager] createFileAtPath:self.targetPath contents:nil attributes:nil];
}
self.dataTask = [self.session dataTaskWithRequest:request];
[self.dataTask resume];
}
- (void)pause {
[self.dataTask cancel];
self.dataTask = nil;
}
- (void)cancel {
[self.dataTask cancel];
self.dataTask = nil;
[self removeFileAtPath: self.targetPath];
}
- (void)removeFileAtPath:(NSString *)filePath {
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:self.targetPath error:&error];
if (error) {
NSLog(@"remove file with error : %@", error);
}
}
#pragma mark - NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
// 判斷下載任務是否完成,然后將結果返回給上層業務。
didCompleteWithError:(nullable NSError *)error {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
if ([httpResponse isKindOfClass:[NSHTTPURLResponse class]]) {
if (httpResponse.statusCode == 200) {
self.checkpoint.etag = [[httpResponse allHeaderFields] objectForKey:@"Etag"];
self.checkpoint.totalExpectedLength = httpResponse.expectedContentLength;
} else if (httpResponse.statusCode == 206) {
self.checkpoint.etag = [[httpResponse allHeaderFields] objectForKey:@"Etag"];
self.checkpoint.totalExpectedLength = self.totalReceivedContentLength + httpResponse.expectedContentLength;
}
}
if (error) {
if (self.failure) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:error.userInfo];
[userInfo oss_setObject:self.checkpoint forKey:@"checkpoint"];
NSError *tError = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
self.failure(tError);
}
} else if (self.success) {
self.success(@{@"status": @"success"});
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)dataTask.response;
if ([httpResponse isKindOfClass:[NSHTTPURLResponse class]]) {
if (httpResponse.statusCode == 200) {
self.checkpoint.totalExpectedLength = httpResponse.expectedContentLength;
} else if (httpResponse.statusCode == 206) {
self.checkpoint.totalExpectedLength = self.totalReceivedContentLength + httpResponse.expectedContentLength;
}
}
completionHandler(NSURLSessionResponseAllow);
}
// 將接收到的網絡數據以追加上傳的方式寫入到文件中,并更新下載進度。
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.targetPath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
self.totalReceivedContentLength += data.length;
if (self.progress) {
self.progress(data.length, self.totalReceivedContentLength, self.checkpoint.totalExpectedLength);
}
}
@end
DownloadRequest定義
#import <Foundation/Foundation.h> typedef void(^DownloadProgressBlock)(int64_t bytesReceived, int64_t totalBytesReceived, int64_t totalBytesExpectToReceived); typedef void(^DownloadFailureBlock)(NSError *error); typedef void(^DownloadSuccessBlock)(NSDictionary *result); @interface Checkpoint : NSObject<NSCopying> @property (nonatomic, copy) NSString *etag; // 資源的ETag值。 @property (nonatomic, assign) unsigned long long totalExpectedLength; // 文件總大小。 @end @interface DownloadRequest : NSObject @property (nonatomic, copy) NSString *sourceURLString; // 下載的URL。 @property (nonatomic, copy) NSString *headURLString; // 獲取文件元數據的URL。 @property (nonatomic, copy) NSString *downloadFilePath; // 文件的本地存儲地址。 @property (nonatomic, copy) DownloadProgressBlock downloadProgress; // 下載進度。 @property (nonatomic, copy) DownloadFailureBlock failure; // 下載成功的回調。 @property (nonatomic, copy) DownloadSuccessBlock success; // 下載失敗的回調。 @property (nonatomic, copy) Checkpoint *checkpoint; // 存儲文件的ETag。 @end @interface DownloadService : NSObject + (instancetype)downloadServiceWithRequest:(DownloadRequest *)request; /** * 啟動下載。 */ - (void)resume; /** * 暫停下載。 */ - (void)pause; /** * 取消下載。 */ - (void)cancel; @end
上層業務調用
- (void)initDownloadURLs { OSSPlainTextAKSKPairCredentialProvider *pCredential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OSS_ACCESSKEY_ID secretKey:OSS_SECRETKEY_ID]; _mClient = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:pCredential]; // 生成用于Get請求的帶簽名的URL。 OSSTask *downloadURLTask = [_mClient presignConstrainURLWithBucketName:@"aliyun-dhc-shanghai" withObjectKey:OSS_DOWNLOAD_FILE_NAME withExpirationInterval:1800]; [downloadURLTask waitUntilFinished]; _downloadURLString = downloadURLTask.result; // 生成用于Head請求的帶簽名的URL。 OSSTask *headURLTask = [_mClient presignConstrainURLWithBucketName:@"aliyun-dhc-shanghai" withObjectKey:OSS_DOWNLOAD_FILE_NAME httpMethod:@"HEAD" withExpirationInterval:1800 withParameters:nil]; [headURLTask waitUntilFinished]; _headURLString = headURLTask.result; } - (IBAction)resumeDownloadClicked:(id)sender { _downloadRequest = [DownloadRequest new]; _downloadRequest.sourceURLString = _downloadURLString; // 設置資源的URL。 _downloadRequest.headURLString = _headURLString; NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; _downloadRequest.downloadFilePath = [documentPath stringByAppendingPathComponent:OSS_DOWNLOAD_FILE_NAME]; // 設置下載文件的本地保存路徑。 __weak typeof(self) wSelf = self; _downloadRequest.downloadProgress = ^(int64_t bytesReceived, int64_t totalBytesReceived, int64_t totalBytesExpectToReceived) { // totalBytesReceived表示當前客戶端已緩存的字節數,totalBytesExpectToReceived表示待下載的總字節數。 dispatch_async(dispatch_get_main_queue(), ^{ __strong typeof(self) sSelf = wSelf; CGFloat fProgress = totalBytesReceived * 1.f / totalBytesExpectToReceived; sSelf.progressLab.text = [NSString stringWithFormat:@"%.2f%%", fProgress * 100]; sSelf.progressBar.progress = fProgress; }); }; _downloadRequest.failure = ^(NSError *error) { __strong typeof(self) sSelf = wSelf; sSelf.checkpoint = error.userInfo[@"checkpoint"]; }; _downloadRequest.success = ^(NSDictionary *result) { NSLog(@"下載成功"); }; _downloadRequest.checkpoint = self.checkpoint; NSString *titleText = [[_downloadButton titleLabel] text]; if ([titleText isEqualToString:@"download"]) { [_downloadButton setTitle:@"pause" forState: UIControlStateNormal]; _downloadService = [DownloadService downloadServiceWithRequest:_downloadRequest]; [_downloadService resume]; } else { [_downloadButton setTitle:@"download" forState: UIControlStateNormal]; [_downloadService pause]; } } - (IBAction)cancelDownloadClicked:(id)sender { [_downloadButton setTitle:@"download" forState: UIControlStateNormal]; [_downloadService cancel]; }
暫?;蛉∠螺d時均能從failure回調中獲取checkpoint。重啟下載時,可以將checkpoint傳到DownloadRequest,然后 DownloadService將使用checkpoint執行一致性校驗。