您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 大檔案下載與斷點續傳的三種實作方案

編輯:iOS 開發綜合

大檔案下載的難點不在「下載」,而在「下載到一半斷了怎麼辦」。本文先比較三種下載寫法,再談斷點續傳的兩種實作。

大檔案下載

方案一:NSURLConnection + NSFileHandle(iOS 9 之後蘋果已不建議使用)

@property (nonatomic, strong) NSFileHandle *writeHandle;
@property (nonatomic, assign) long long totalLength;

1. 發送請求:

// 建立請求
NSURL *url = [NSURL URLWithString:@""];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 以 NSURLConnection 發起非同步請求
[NSURLConnection connectionWithRequest:request delegate:self];

2. 在代理方法中處理回傳資料:

/**
 * 收到服務器響應時呼叫
 * 1. 建立一個空檔案
 * 2. 用一個句柄關聯這個空檔案,方便往後面追加資料
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response {
    // 建立檔案路徑
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [caches stringByAppendingPathComponent:@"videos.zip"];

    // 在沙盒中建立空檔案
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:filePath contents:nil attributes:nil];

    // 建立寫入用的檔案句柄
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    // 取得檔案總大小
    self.totalLength = response.expectedContentLength;
}

/**
 * 收到部分資料時呼叫
 * 用句柄把資料追加到檔案末尾
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data {
    [self.writeHandle seekToEndOfFile]; // 移到檔案末尾
    [self.writeHandle writeData:data];  // 寫入沙盒
}

/** 全部資料接收完畢,關閉句柄 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}

方案二:NSURLSessionDownloadTask + NSFileManager

最省事的一種。系統會先把檔案寫到 tmp,下載完成後給你一個臨時路徑,自己搬到家目錄即可。

NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@""];

// 適合下載大檔案,資料會先存在沙盒的 tmp 目錄
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    // location:暫存檔案的路徑(已下載完成的檔案)

    // 建立存放路徑
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    // response.suggestedFilename:建議使用的檔名,通常與服務器端一致
    NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];

    // 把暫存檔案移動(或複製)到 Caches 目錄
    // atPath:搬移前的路徑 toPath:搬移後的路徑
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr moveItemAtPath:location.path toPath:file error:nil];
}];

[task resume];

方案三:NSURLSessionDownloadDelegate

需要隨時掌握進度時用這個,因為它有完整的進度回呼。

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 建立下載任務並設定代理
    NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg
                                                          delegate:self
                                                     delegateQueue:[NSOperationQueue mainQueue]];
    NSURL *url = [NSURL URLWithString:@""];
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
    [task resume];
}

#pragma mark -

/** 下載完畢後呼叫;location 是暫存檔案路徑 */
- (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];

    // 把暫存檔案搬移到 Caches 目錄
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr moveItemAtPath:location.path toPath:file error:nil];
}

/**
 * 每下載完一部分就會呼叫(可能被呼叫多次)
 * bytesWritten              本次寫入了多少
 * totalBytesWritten         目前累計寫入多少
 * totalBytesExpectedToWrite 檔案總大小
 */
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    // 在這裡更新進度條
}

/** 恢復下載時使用 */
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
    // 用於斷點續傳
}

要注意的是,didFinishDownloadingToURL: 的實作必須跑在 delegate 佇列上;若改用 completionHandler 版本,這個回呼不會被觸發。

斷點續傳

方案一:在 NSURLConnection 版本上加兩個變數

@property (nonatomic, assign) long long currentLength;
@property (nonatomic, strong) NSURLConnection *conn;

在 didReceiveData: 中累計已下載長度:

// 記錄斷點:累計檔案長度
self.currentLength += data.length;

用一個按鈕負責「開始/繼續」與「暫停」:

- (IBAction)download:(UIButton *)sender {
    sender.selected = !sender.isSelected;

    if (sender.selected) {
        // 繼續(或開始)下載
        NSURL *url = [NSURL URLWithString:@""];
        // ★關鍵:使用 NSMutableURLRequest,並設定 Range 請求標頭
        NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
        NSString *range = [NSString stringWithFormat:@"bytes=%lld-", self.currentLength];
        [mRequest setValue:range forHTTPHeaderField:@"Range"];
        // 下載
        self.conn = [NSURLConnection connectionWithRequest:mRequest delegate:self];
    } else {
        [self.conn cancel];
        self.conn = nil;
    }
}

最後,在 didReceiveResponse: 的第一行加上防重複建立空檔的判斷:

if (self.currentLength) return;

方案二:NSURLSessionDownloadDelegate + resumeData

這是更現代的寫法,暫停時系統會給你一塊 resumeData,裡面包著續傳位置與 URL,恢復時再餵回去即可。

@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSData *resumeData; // 含續傳起始位置與下載 URL
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
// 懶加載 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:@""];
    self.task = [self.session downloadTaskWithURL:url];
    [self.task resume];
}

// 暫停
- (void)pause {
    __weak typeof(self) vc = self;
    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        // resumeData 含續傳起始位置與下載 URL
        vc.resumeData = resumeData;
        vc.task = nil;
    }];
}

// 恢復
- (void)resume {
    // 傳入上次暫停時取得的資料即可續傳
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    [self.task resume];
    // 清空
    self.resumeData = nil;
}

#pragma mark - NSURLSessionDownloadDelegate

/** 下載完畢後呼叫;location 是暫存檔案路徑 */
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

    NSFileManager *mgr = [NSFileManager defaultManager];
    [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 {
    // 在這裡更新進度條
}

/** 恢復下載時使用 */
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
}

幾個實務提醒

斷點續傳能成立的前提是伺服器回應了 Accept-Ranges: bytes,並正確處理 Range 請求、回 206 Partial Content。若伺服器不支持,用戶端寫得再好也沒用。

另外,resumeData 是系統給的不透明資料,不要自己拼湊;App 被中止後它仍然有效,可以存到 Caches 裡下次啟動再續傳。

最後,下載任務請勿放在 Caches 以外的地方暫存過久,並記得在 didFinishDownloadingToURL: 中把檔案搬到正式位置——系統有權隨時清理 tmp 目錄。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved