您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 大檔案下載實戰:寫檔策略、斷點續傳與 NSURLSession 下載

編輯:iOS 相關資訊

為什麼大檔案要特別處理

小檔案直接把回應資料收在記憶體裡沒問題,但下載幾百 MB 的影片時,這個做法會迅速吃光記憶體,嚴重時 App 會被系統強制終止。此外,網路不穩導致中途斷線是常態,若沒有記錄中斷位置,使用者就得從頭再下一次,白白浪費流量。

因此大檔案下載有兩個核心課題:邊下載邊落盤,以及記錄中斷點以便續傳。

方案一:NSURLConnection 搭配 NSFileHandle

NSURLConnection 本身不支援斷點續傳,但透過 delegate 的三個階段回呼,可以自行完成寫檔與位置記錄。

// 相關屬性
/** 檔案總長度 */
@property (nonatomic, assign) NSInteger contentLength;
/** 已下載長度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 檔案句柄,用於寫入 */
@property (nonatomic, strong) NSFileHandle *handle;

// 建立並送出請求
NSURL *url = [NSURL URLWithString:@"此處為 URL 字串"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
#pragma mark - NSURLConnectionDataDelegate

// 收到回應:此時才知道檔案總大小
- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSHTTPURLResponse *)response {
    self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];

    // 在 Caches 目錄下建立檔案
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                            NSUserDomainMask, YES) lastObject]
                          stringByAppendingPathComponent:@"minion_15.mp4"];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

    self.handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
}

// 收到資料:逐段附加到檔案尾端,避免在記憶體中累積
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.handle seekToEndOfFile];
    [self.handle writeData:data];

    self.currentLength += data.length;
    CGFloat progress = 1.0 * self.currentLength / self.contentLength;
}

// 下載完成:關閉並清空句柄
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.handle closeFile];
    self.handle = nil;
    self.currentLength = 0;
}

若偏好使用 NSOutputStream,寫檔部分可改寫如下:

@property (nonatomic, strong) NSOutputStream *stream;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                       NSUserDomainMask, YES) lastObject];
    NSString *filePath = [cache stringByAppendingPathComponent:response.suggestedFilename];

    // append:YES 代表從檔案尾端續寫
    self.stream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
    [self.stream open];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.stream write:[data bytes] maxLength:data.length];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.stream close];
}

方案二:NSURLSession(支援斷點續傳)

NSURLSession 的 download task 會自動把資料寫進沙盒的 tmp 目錄,並由系統自行維護中斷點,實作斷點續傳的難度大幅降低。需要注意的是 tmp 裡的檔案會被系統週期性清理,因此下載完成後必須搬到家目錄(通常是 Caches)長期保存。

@property (nonatomic, strong) NSURLSessionDownloadTask *task;

// 取得 session 並設定 delegate
NSURLSession *session =
    [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                  delegate:self
                             delegateQueue:[[NSOperationQueue alloc] init]];

// 建立下載任務
self.task = [session downloadTaskWithURL:(此處為下載檔案的 URL)];

// 每寫入一次暫存檔就會回呼,用於更新進度
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    CGFloat progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
}

// 續傳時回呼,fileOffset 即中斷時的位移量
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
}

// 完成時把檔案搬到可長期保存的位置
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
                       NSUserDomainMask, YES) lastObject]
                      stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager moveItemAtURL:location
                         toURL:[NSURL fileURLWithPath:file]
                         error:nil];
}

// 控制任務狀態
[self.task resume];    // 開始或續傳
[self.task suspend];   // 暫停

實務補充

要真正做到跨 App 啟動的續傳,需要在 didCompleteWithError: 中把 userInfo 裡的 NSURLSessionTransferSize 與 resume data 存起來,下次以 downloadTaskWithResumeData: 還原。純粹只是「本次執行期間暫停再續傳」的話,用 suspend/resume 就够了。

另外,若希望 App 被切到背景後下載仍持續,應改用 backgroundSessionConfigurationWithIdentifier: 建立背景 session,並在 App 完成所有背景任務時呼叫 backgroundSessionCompletionHandler,否則系統會不信任你的下載狀態。

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