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

用 ASIHTTPRequest 與 Range 請求頭實現斷點續傳

編輯:iOS 開發綜合

網路上常見用 [request setAllowResumeForFileDownloads:YES]; 來做續傳的說法,但它並不是真正意義上的斷點續傳——它只能讓應用在「下載過程中」暫停與繼續,一旦退出應用再進來就失效了。不過,透過 ASIHTTPRequest 的異步請求與 delegate,還是可以實現真正的斷點續傳。本文以 Grails 撰寫的斷點續傳伺服器端為例。

異步請求的程式碼:

-(void) doSimpleGetBinary{

    NSURL *url = [NSURL URLWithString:@"https://localhost:8080/BookProto/book/image"];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    [request setRequestMethod:@"GET"];

    //[request addRequestHeader:@"Range" value:@"bytes=3-"];

    [request setDelegate:self];

    [request startAsynchronous];

}

這裡設定了 delegate,需在標頭檔中實作相應的 protocol:

@interface CFHttpDemoViewController : UIViewController<ASIProgressDelegate> {

本例用到 delegate 的以下方法。

requestFinished:異步請求結束後呼叫。

- (void)requestFinished:(ASIHTTPRequest *)request{

    NSLog(@"response status code: %i",[request responseStatusCode]);

    NSLog(@"response content length: %@",[[request responseHeaders] objectForKey:@"Content-Length" ]);

    NSLog(@"request finished.");

    label.text=@"request finished.";

}

下面的方法在緩衝區收到部分資料後呼叫,看起來是每隔一段毫秒就觸發一次,並傳入緩衝區的 NSData 物件。

-(void)request:(ASIHTTPRequest *)request

didReceiveData:(NSData *)data{

    NSLog(@"did receive data, data length: %i",[data length]);

    //複製到位元組陣列中

    Byte *byteData=(Byte *)malloc([data length]);

    memcpy(byteData,[data bytes],[data length]);

    for (int i=0; i<=10; i++) {

       NSLog(@"%i: %i",i+1,byteData[i]);

    }

    free(byteData);

    [request cancel];

    label.text=@"canceled.";

}

執行時,分別屏蔽與取消屏蔽 [request addRequestHeader:@"Range" value:@"bytes=3-"]; 這行,可以看到回傳資料的變化:加上 Range 請求頭後,狀態碼由 200 變成 206(Partial Content),且收到的第一個位元組從頭開始變成從第 3 個位元組之後,這正是伺服器依 Range 回傳部分內容的證明。

2. NSURLConnection 實現斷點續傳的關鍵,是自訂 http request 的 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(OK)返回。

在 iOS 中用 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"];

接著把收到的資料以「附加」模式寫入檔案,關鍵是 fopen 時使用 "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];

    }else {

    NSLog(@"file exist!!!");

    }

    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);

}

整體思路就是:紀錄已下載的位元組數,透過 Range 請求頭只抓取剩下的部分,再以附加模式續寫到本地檔案,如此即使中斷後重新連線,也能從中斷處繼續下載。

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