Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

iOS 斷點續傳實作:用 NSURLConnection 搭配 Range 請求頭

以 NSURLConnection 實作斷點續傳,關鍵只有一件事:自訂 HTTP 請求的 Range 表頭,只向伺服器索取尚未下載的那一段。

Range 表頭怎麼寫

Range 可以指定一個或多個子範圍:

  • 前 500 位元組:bytes=0-499
  • 第二段 500 位元組:bytes=500-999
  • 最後 500 位元組:bytes=-500
  • 第 500 位元組之後:bytes=500-
  • 第一個與最後一個位元組:bytes=0-0,-1
  • 同時指定多段:bytes=500-600,601-999

伺服器有權忽略這個表頭;若無條件 GET 帶了 Range,正確的回應狀態碼是 206 Partial Content 而非 200。實作時務必檢查狀態碼,否則可能把完整檔案重複附加一次。

以 NSMutableURLRequest 設定

NSURL *url1 = [NSURL URLWithString:@"下載地址"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url1];

[request1 setValue:@"bytes=20000-" forHTTPHeaderField:@"Range"];
[request1 setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

NSData *returnData1 = [NSURLConnection sendSynchronousRequest:request1
                                            returningResponse:nil
                                                        error:nil];
[self writeToFile:returnData1 fileName:@"SOMEPATH"];

以附加模式寫入檔案

續傳的本質是「往既有檔案尾巴接上」,因此要用 "ab+" 模式開檔並把指針移到結尾:

- (void)writeToFile:(NSData *)data fileName:(NSString *)fileName {
    NSString *filePath = [NSString stringWithFormat:@"%@", fileName];

    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO) {
        NSLog(@"file not exist, create it...");
        [[NSFileManager defaultManager] createFileAtPath:filePath
                                               contents:nil
                                             attributes:nil];
    }

    FILE *file = fopen([fileName UTF8String], [@"ab+" UTF8String]);
    if (file != NULL) {
        fseek(file, 0, SEEK_END);
    }

    int readSize = [data length];
    fwrite((const void *)[data bytes], readSize, 1, file);
    fclose(file);
}

別忘了的細節

正式實作時,起始位置應由「本地檔案現有大小」推算,而不是寫死 20000;下載完成後要依 Content-Length 或 206 回應判定是否收尾。同步請求只適合簡單情境,大檔下載建議改用非同步的 sendAsynchronousRequest: 或 delegate 回呼,以免卡住主執行緒。

Copyright © Linux教程網 All Rights Reserved