iOS開(kāi)發(fā)ASIHTTPRequest斷點(diǎn)續(xù)傳(下載)
本文為大家介紹了iOS開(kāi)發(fā)ASIHTTPRequest斷點(diǎn)續(xù)傳(下載)的內(nèi)容,其中包括ASIHTTPRequest可以恢復(fù)中斷的下載,設(shè)置一個(gè)臨時(shí)下載路徑,斷點(diǎn)續(xù)傳的工作原理等等內(nèi)容。
從0.94版本開(kāi)始,ASIHTTPRequest可以恢復(fù)中斷的下載。
這個(gè)特性只對(duì)下載數(shù)據(jù)到文件中有效,你必須為一下情況的request設(shè)置allowResumeForFileDownloads 為YES:
- 任何你希望將來(lái)可以斷點(diǎn)續(xù)傳的下載(否則,ASIHTTPRequest會(huì)在取消或者釋放內(nèi)存時(shí)將臨時(shí)文件刪除)
- 任何你要進(jìn)行斷點(diǎn)續(xù)傳的下載
另外,你必須自己設(shè)置一個(gè)臨時(shí)下載路徑(setTemporaryFileDownloadPath),這個(gè)路徑是未完成的數(shù)據(jù)的路徑。新的數(shù)據(jù)將會(huì)被添加到這個(gè)文件,當(dāng)下載完成時(shí),這個(gè)文件將被移動(dòng)到downloadDestinationPath 。
- - (IBAction)resumeInterruptedDownload:(id)sender
- {
- NSURL *url = [NSURL URLWithString:
- @"http://www.dreamingwish.com/wp-content/uploads/2011/10/asihttprequest-auth.png"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- NSString *downloadPath = @"/Users/ben/Desktop/asi.png";
- //當(dāng)request完成時(shí),整個(gè)文件會(huì)被移動(dòng)到這里
- [request setDownloadDestinationPath:downloadPath];
- //這個(gè)文件已經(jīng)被下載了一部分
- [request setTemporaryFileDownloadPath:@"/Users/ben/Desktop/asi.png.download"];
- [request setAllowResumeForFileDownloads:YES];
- [request startSynchronous];
- //整個(gè)文件將會(huì)在這里
- NSString *theContent = [NSString stringWithContentsOfFile:downloadPath];
- }
斷點(diǎn)續(xù)傳的工作原理是讀取temporaryFileDownloadPath的文件的大小,并使用Range: bytes=x HTTP頭來(lái)請(qǐng)求剩余的文件內(nèi)容。
ASIHTTPRequest并不檢測(cè)是否存在Accept-Ranges頭(因?yàn)轭~外的HEAD頭請(qǐng)求會(huì)消耗額外的資源),所以只有確定服務(wù)器支持?jǐn)帱c(diǎn)續(xù)傳下載時(shí),再使用這個(gè)特性。