以 NSURLConnection 實作斷點續傳,關鍵只有一件事:自訂 HTTP 請求的 Range 表頭,只向伺服器索取尚未下載的那一段。
Range 可以指定一個或多個子範圍:
bytes=0-499bytes=500-999bytes=-500bytes=500-bytes=0-0,-1bytes=500-600,601-999伺服器有權忽略這個表頭;若無條件 GET 帶了 Range,正確的回應狀態碼是 206 Partial Content 而非 200。實作時務必檢查狀態碼,否則可能把完整檔案重複附加一次。
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 回呼,以免卡住主執行緒。