全部產品
Search
文件中心

Object Storage Service:iOS斷點續傳下載

更新時間:Aug 28, 2024

斷點續傳下載是指用戶端在從網路上下載資源時,由於某種原因中斷下載。再次開啟下載時可以從已下載完成的部分開始繼續下載未完成的部分,從而節省時間和流量。

流程說明

在手機端使用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中攜帶RangeIf-Match,OSS Server收到請求後會驗證If-Match中的ETag值。如果不匹配,則返回412 precondition狀態代碼。

  • OSS Server針對GetObject目前已支援RangeIf-MatchIf-None-MatchIf-Modified-SinceIf-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];
    }
說明

暫停或取消下載時均能從failure回調中擷取checkpoint。重啟下載時,可以將checkpoint傳到DownloadRequest,然後 DownloadService將使用checkpoint執行一致性校正。