近期做小專案時,發現用 NSURLSession 或 AFN 進行斷點續傳有諸多不便,於是自行封裝了一個類來實現。它能在程式重啟後繼續下載(需自行呼叫方法),也可同時多次呼叫。使用時請注意傳入參數的合理性,方法內部並未對參數做修正。主要技術:NSURLConnection、block、NSFileHandle。
typedef void (^DownloadServiceSuccess)(NSString *savePath);
typedef void (^DownloadServiceFailure)(NSError *error);
@interface DownloadService : NSObject
+ (void)downLoadWithURL:(NSString *)urlStr toDirectory:(NSString *)toDirectory
cacheCapacity:(NSUInteger)capacity
success:(DownloadServiceSuccess)success
failure:(DownloadServiceFailure)failure;
@end
關鍵在於:先檢查本地檔案是否存在,若存在則取得其大小作為起始位置,並透過設定請求的 Range 標頭向伺服器請求剩餘部分,从而实现續傳:
+ (void)downLoadWithURL:(NSString *)urlStr toDirectory:(NSString *)toDirectory
cacheCapacity:(NSInteger)capacity
success:(DownloadServiceSuccess)success
failure:(DownloadServiceFailure)failure {
// 1. 建立檔案
NSString *fileName = [urlStr lastPathComponent];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", toDirectory, fileName];
unsigned long long from = 0;
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
from = [[NSData dataWithContentsOfFile:filePath] length];
} else {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0f];
// 設置 Range 請求頭,实现續傳
NSString *rangeValue = [NSString stringWithFormat:@"bytes=%llu-", from];
[request addValue:rangeValue forHTTPHeaderField:@"Range"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:_download];
_dictPath[connection.description] = filePath;
// 保存 block 用於回調
myBlcok block = ^(NSString *savePath, NSError *error){
if (error) { if (failure) failure(error); }
else { if (success) success(savePath); }
};
_dictBlock[connection.description] = block;
_cacheCapacity = capacity * 1024 * 1024;
[connection start];
}
收到伺服器回應時,開啟檔案以準備寫入:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSString *filePath = _dictPath[connection.description];
NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
_dictHandle[connection.description] = outFile;
}
接收資料時,把游標移到檔尾並依緩衝區大小寫入檔案:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSFileHandle *outFile = _dictHandle[connection.description];
[outFile seekToEndOfFile];
[_cacheData appendData:data];
if (_cacheData.length >= _cacheCapacity) {
[outFile writeData:data];
[_cacheData setLength:0];
}
}
無論成功或失敗,都要關閉檔案、回呼 block 並清理字典:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSFileHandle *outFile = _dictHandle[connection.description];
[outFile closeFile];
myBlcok block = _dictBlock[connection.description];
if (block) block(nil, error);
[_dictHandle removeObjectForKey:connection.description];
[_dictPath removeObjectForKey:connection.description];
[_dictBlock removeObjectForKey:connection.description];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSFileHandle *outFile = _dictHandle[connection.description];
[outFile closeFile];
NSString *savePath = [_dictPath objectForKey:connection.description];
myBlcok block = _dictBlock[connection.description];
if (block) block(savePath, nil);
}
核心思路就是透過 Range 標頭與 NSFileHandle 定位寫入,讓下載中斷後能從既有大小續傳。