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

iOS 網路編程:自製支援斷點續傳的下載類別

編輯:iOS 相關資訊

近期在處理一個小專案時,發現無論用 NSURLSession 還是 AFNetworking 做斷點續傳都有諸多不便,於是乾脆自己封裝了一個類別來實現。這個 DownloadService 有幾個特點:程式重啟後仍能繼續下載(需自行呼叫方法),並支援同時多次呼叫。使用時請注意傳入參數的合理性,方法內部並未對參數做修正。

主要技術:NSURLConnection、block、NSFileHandle。

一、DownloadService.h

#import <Foundation/Foundation.h>

typedef void (^DownloadServiceSuccess)(NSString *savePath);
typedef void (^DownloadServiceFailure)(NSError *error);

@interface DownloadService : NSObject

/**
 * 下載指定 URL 的資源到指定路徑
 * @param urlStr       網路資源路徑
 * @param toDirectory  本地儲存檔案夾
 * @param capacity     緩衝大小(單位 MB)
 * @param success      成功時回傳本地儲存路徑
 * @param failure      失敗時回呼的錯誤原因
 */
+ (void)downLoadWithURL:(NSString *)urlStr
           toDirectory:(NSString *)toDirectory
         cacheCapacity:(NSUInteger)capacity
               success:(DownloadServiceSuccess)success
               failure:(DownloadServiceFailure)failure;

@end

二、DownloadService.m

#import "DownloadService.h"

static DownloadService *_download;
static NSMutableDictionary *_dictPath;    // 儲存檔案路徑
static NSMutableDictionary *_dictBlock;   // 儲存 block
static NSMutableDictionary *_dictHandle;  // 儲存 NSFileHandle
static unsigned long long _cacheCapacity; // 緩衝大小
static NSMutableData *_cacheData;

typedef void (^myBlcok)(NSString *savePath, NSError *error);

@interface DownloadService () <NSURLConnectionDataDelegate>
@end

@implementation DownloadService

+ (void)initialize
{
    _download = [[DownloadService alloc] init];
    _dictPath   = [NSMutableDictionary dictionary];
    _dictBlock  = [NSMutableDictionary dictionary];
    _dictHandle = [NSMutableDictionary dictionary];
    _cacheData  = [NSMutableData data];
}

+ (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];
    }

    // 2. 組裝請求,透過 Range 標頭告知伺服器要從哪裡續傳
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request =
        [NSMutableURLRequest requestWithURL:url
                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                            timeoutInterval:5.0f];
    NSString *rangeValue = [NSString stringWithFormat:@"bytes=%llu-", from];
    [request addValue:rangeValue forHTTPHeaderField:@"Range"];

    // 3. 建立連線
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:_download];
    _dictPath[connection.description] = filePath;

    // 4. 保存回呼 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];
    }
}

// 連線出錯
- (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); }

    [_dictHandle removeObjectForKey:connection.description];
    [_dictPath   removeObjectForKey:connection.description];
    [_dictBlock  removeObjectForKey:connection.description];
}

@end

續傳原理小結

斷點續傳的關鍵在於 HTTP 的 Range 請求標頭。每次下載前先檢查本機檔案已存在多少位元組,把這個大小以 bytes=起始位置- 的形式帶入請求,伺服器就會從該位置接續傳輸。搭配 NSFileHandle 的 seekToEndOfFile 把新資料附加到檔案結尾,即可實現無縫續傳。

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