您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 網路程式設計:自己封裝一個斷點續傳下載器

編輯:iOS 開發綜合

前言

下載是專案裡常見的需求。小檔案(圖片、文字)一次抓完就好;但遇到大型音檔、影片,使用者可能下到一半就關掉 App,回家再繼續。這時候就需要斷點續傳,讓下載能從上次的中斷處接著走。

目標是封裝一個類別,做到:呼叫一個介面就能下載並取得進度、成功後知道檔案位置、失敗時知道原因、可以暫停後續傳。

原理

斷點續傳的關鍵是 HTTP/1.1(RFC2616)定義的 Range 與 Content-Range 兩個標頭。最簡單的流程是:

    1. 客戶端下載一個 1024K 的檔案,已下載 512K。

    2. 連線中斷後要續傳,於請求標頭帶上 Range: bytes=512000-,通知伺服器從這個位置開始傳。

    3. 伺服器從 512K 處續傳,回應標頭帶 Content-Range: bytes 512000-1024000/1024000,且狀態碼應為 206 而非 200。

三個要解決的問題

1. 客戶端如何知道已經下載多少位元組

直接問檔案系統要檔案大小即可:

 [[[NSFileManager defaultManager] attributesOfItemAtPath:FileStorePath error:nil][NSFileSize] integerValue]

2. 如何知道檔案總共多少位元組

這裡要用回應標頭的 Content-Length。它描述的是訊息本文的傳輸長度,在沒有壓縮的情況下就等於檔案的位元組數。

要注意的是,續傳時伺服器回傳的 Content-Length 只是「這次要傳的部分」。因此檔案總大小 = 已下載大小 + Content-Length。這個總數需要存起來,這裡用 plist 記錄,並以 url 的 hash 值作為檔名,避免重複:

 - (void)URLSession:(NSURLSession *)session
           dataTask:(NSURLSessionDataTask *)dataTask
 didReceiveResponse:(NSHTTPURLResponse *)response
  completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
     self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + DownloadLength;
     NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:TotalLengthPlist];
     if (dict == nil) dict = [NSMutableDictionary dictionary];
     dict[Filename] = @(self.totalLength);
     [dict writeToFile:TotalLengthPlist atomically:YES];
 }

這個 delegate 方法在每次收到回應時呼叫一次,正是取出標頭的時機。

3. 把進度、成功、失敗包成回呼

可以參考 AFNetworking 的做法,用幾個 block 把三種結果往外丟:

 - (void)downLoadWithURL:(NSString *)URL
                 progress:(progressBlock)progressBlock
                  success:(successBlock)successBlock
                    faile:(faileBlock)faileBlock {
     self.successBlock  = successBlock;
     self.failedBlock   = faileBlock;
     self.progressBlock = progressBlock;
     self.downLoadUrl   = URL;
     [self.task resume];
 }

完整實作

標頭檔:

 #import <Foundation/Foundation.h>

 typedef void (^successBlock)(NSString *fileStorePath);
 typedef void (^faileBlock)(NSError *error);
 typedef void (^progressBlock)(float progress);

 @interface DownLoadManager : NSObject <NSURLSessionDataDelegate>
 @property (copy) successBlock successBlock;
 @property (copy) faileBlock failedBlock;
 @property (copy) progressBlock progressBlock;

 - (void)downLoadWithURL:(NSString *)URL
                progress:(progressBlock)progressBlock
                 success:(successBlock)successBlock
                   faile:(faileBlock)faileBlock;
 + (instancetype)sharedInstance;
 - (void)stopTask;
 @end

實作檔:

 #import "DownLoadManager.h"
 #import "NSString+Hash.h"

 @interface DownLoadManager ()
 /** 下載任務 */
 @property (nonatomic, strong) NSURLSessionDataTask *task;
 @property (nonatomic, strong) NSURLSession *session;
 /** 寫檔用的輸出流 */
 @property (nonatomic, strong) NSOutputStream *stream;
 /** 檔案總大小 */
 @property (nonatomic, assign) NSInteger totalLength;
 @property (nonatomic, strong) NSString *downLoadUrl;
 @end

 // 檔名:用 url 的 md5 保證唯一
 #define Filename self.downLoadUrl.md5String
 // 存放路徑(Caches)
 #define FileStorePath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:Filename]
 // 用 plist 記錄各檔的總大小
 #define TotalLengthPlist [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"totalLength.plist"]
 // 已下載大小
 #define DownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:FileStorePath error:nil][NSFileSize] integerValue]

 @implementation DownLoadManager

 #pragma mark - 單例
 static id _instance;

 + (instancetype)allocWithZone:(struct _NSZone *)zone {
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
         _instance = [super allocWithZone:zone];
     });
     return _instance;
 }

 + (instancetype)sharedInstance {
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
         _instance = [[self alloc] init];
     });
     return _instance;
 }

 - (id)copyWithZone:(NSZone *)zone { return _instance; }
 - (id)mutableCopyWithZone:(NSZone *)zone { return _instance; }

 #pragma mark - 公開方法
 - (void)downLoadWithURL:(NSString *)URL
                progress:(progressBlock)progressBlock
                 success:(successBlock)successBlock
                   faile:(faileBlock)faileBlock {
     self.successBlock  = successBlock;
     self.failedBlock   = faileBlock;
     self.progressBlock = progressBlock;
     self.downLoadUrl   = URL;
     [self.task resume];
 }

 - (void)stopTask {
     [self.task suspend];
 }

 #pragma mark - Getter
 - (NSURLSession *)session {
     if (!_session) {
         _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                 delegate:self
                                            delegateQueue:[[NSOperationQueue alloc] init]];
     }
     return _session;
 }

 - (NSOutputStream *)stream {
     if (!_stream) {
         _stream = [NSOutputStream outputStreamToFileAtPath:FileStorePath append:YES];
     }
     return _stream;
 }

 - (NSURLSessionDataTask *)task {
     if (!_task) {
         NSInteger totalLength = [[NSDictionary dictionaryWithContentsOfFile:TotalLengthPlist][Filename] integerValue];
         if (totalLength && DownloadLength == totalLength) {
             NSLog(@"###### 檔案已經下載過了");
             return nil;
         }
         NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.downLoadUrl]];
         // 從已下載的位置一路要到底
         NSString *range = [NSString stringWithFormat:@"bytes=%zd-", DownloadLength];
         [request setValue:range forHTTPHeaderField:@"Range"];
         _task = [self.session dataTaskWithRequest:request];
     }
     return _task;
 }

 #pragma mark - <NSURLSessionDataDelegate>

 /** 1. 收到回應 */
 - (void)URLSession:(NSURLSession *)session
            dataTask:(NSURLSessionDataTask *)dataTask
  didReceiveResponse:(NSHTTPURLResponse *)response
   completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
     [self.stream open];
     /* Content-Length 是伺服器「這一次」要傳的長度。
        首次請求檔案 A(1000 byte),回傳 1000;下到 500 byte 中斷,
        再請求 Range: bytes=500-,此時回傳 500。
        所以斷點續傳時,總大小必須把兩者相加。 */
     self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + DownloadLength;

     NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:TotalLengthPlist];
     if (dict == nil) dict = [NSMutableDictionary dictionary];
     dict[Filename] = @(self.totalLength);
     [dict writeToFile:TotalLengthPlist atomically:YES];

     completionHandler(NSURLSessionResponseAllow);
 }

 /** 2. 收到資料(會被呼叫多次) */
 - (void)URLSession:(NSURLSession *)session
            dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data {
     [self.stream write:data.bytes maxLength:data.length];
     float progress = 1.0 * DownloadLength / self.totalLength;
     if (self.progressBlock) {
         self.progressBlock(progress);
     }
 }

 /** 3. 請求結束 */
 - (void)URLSession:(NSURLSession *)session
                task:(NSURLSessionTask *)task
 didCompleteWithError:(NSError *)error {
     if (error) {
         if (self.failedBlock) self.failedBlock(error);
         self.stream = nil;
         self.task = nil;
     } else {
         if (self.successBlock) self.successBlock(FileStorePath);
         [self.stream close];
         self.stream = nil;
         self.task = nil;
     }
 }

 @end

呼叫方式

 @interface ViewController ()
 @end

 @implementation ViewController

 /** 開始下載 */
 - (IBAction)start:(id)sender {
     NSString *downLoadUrl = @"https://audio.xmcdn.com/group11/M01/93/AF/wKgDa1dzzJLBL0gCAPUzeJqK84Y539.m4a";
     [[DownLoadManager sharedInstance] downLoadWithURL:downLoadUrl progress:^(float progress) {
         NSLog(@"### %f", progress);
     } success:^(NSString *fileStorePath) {
         NSLog(@"### %@", fileStorePath);
     } faile:^(NSError *error) {
         NSLog(@"### %@", error.userInfo[NSLocalizedDescriptionKey]);
     }];
 }

 /** 暫停下載 */
 - (IBAction)pause:(id)sender {
     [[DownLoadManager sharedInstance] stopTask];
 }

 @end

接著可以做什麼

目前這個版本只支援單一任務。要擴充成多任務,可以改成以 url 為 key 維護一个字典,各自持有 task 與 stream;另外把記錄用的 plist 換成 SQLite,在檔案數量多時會更穩定。這兩件事做完,一個夠用的下載器就成形了。

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