IOS開發網絡篇之──ASIHTTPRequest下載示例(支持斷點續傳)

在工程中,我們會常常遇到需要下載的程序,比如下載在線音樂、下載圖片等等,今天我將介紹一下利用ASIHTTPRequest的下載示例,支持斷點續傳,利用ASIHTTPRequest下載以及斷點續傳的原理在我的博客:http://blog.csdn.net/pjk1129/article/details/6575588中有具體的介紹,今天重點介紹如何實現,廢話少說,開始正文:

    一、創建網絡請求隊列

    首先,創建網絡請求隊列,如下:

    ASINetworkQueue   *que = [[ASINetworkQueue alloc] init];

    self.netWorkQueue = que;

    [que release];

    

    [self.netWorkQueue reset];

    [self.netWorkQueue setShowAccurateProgress:YES];

    [self.netWorkQueue go];

  二、創建存放路徑

    //初始化Documents路徑

NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

//初始化臨時文件路徑

NSString *folderPath = [path stringByAppendingPathComponent:@"temp"];

//創建文件管理器

NSFileManager *fileManager = [NSFileManager defaultManager];

//判斷temp文件夾是否存在

BOOL fileExists = [fileManager fileExistsAtPath:folderPath];

if (!fileExists) {//如果不存在說創建,因爲下載時,不會自動創建文件夾

[fileManager createDirectoryAtPath:folderPath 

               withIntermediateDirectories:YES 

                                attributes:nil

                                     error:nil];

}

        三、發送下載請求

        這裏對下面幾個對象說明一下:CustomCell是我自定義的cell,cell上面有下載和暫停兩個按鈕,其tag值爲cell所在的行,因此這裏的[sendertag]爲下載按鈕的tag值,self.downloadArray爲array數組對象,存放要下載的資源字典信息,在該字典中有一鍵爲URL,它對應的值就是我們下載鏈接。

   這些東西,根據自己的實際需要改動一下即可使用

    CustomCell *cell = (CustomCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[sender tag] inSection:0]];

    NSString  *filePath = [[self.downloadArray objectAtIndex:[sender tag]] objectForKey:@"URL"];

    NSLog(@"filePath=%@",filePath);

    //初始下載路徑

NSURL *url = [NSURL URLWithString:filePath];

//設置下載路徑

ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];

//設置ASIHTTPRequest代理

request.delegate = self;

    //初始化保存ZIP文件路徑

NSString *savePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"book_%d.zip",[sender tag]]];

//初始化臨時文件路徑

NSString *tempPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"temp/book_%d.zip.temp",[sender tag]]];

//設置文件保存路徑

[request setDownloadDestinationPath:savePath];

//設置臨時文件路徑

[request setTemporaryFileDownloadPath:tempPath];

    

    //設置進度條的代理,

[request setDownloadProgressDelegate:cell];

//設置是是否支持斷點下載

[request setAllowResumeForFileDownloads:YES];

//設置基本信息

[request setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:[sender tag]],@"bookID",nil]];

    

    NSLog(@"UserInfo=%@",request.userInfo);

//添加到ASINetworkQueue隊列去下載

[self.netWorkQueue addOperation:request];

//收回request

[request release];

    三、暫停請求

    這裏的cell下下載時的一樣,

CustomCell *cell = (CustomCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:[sender tag] inSection:0]];

    

    for (ASIHTTPRequest *request in [self.netWorkQueue operations]) {

        NSInteger bookid = [[request.userInfo objectForKey:@"bookID"] intValue];//查看userinfo信息

        if ([sender tag] == bookid) {//判斷ID是否匹配

            //暫停匹配對象

            [request clearDelegatesAndCancel];

        }

    }


    四、ASIHTTPRequestDelegate回調方法

          上面已經把下載請求與暫停請求實現,點擊下載時,開始下載資源;當點暫停時,下載中斷;當我們再點擊下載按鈕時,繼續下載,在第二步的

[request setAllowResumeForFileDownloads:YES]設置是是否支持斷點下載。下面要實現ASIHTTPRequestDelegate代理方法如下:

#pragma mark -

#pragma mark ASIHTTPRequestDelegate method

//ASIHTTPRequestDelegate,下載之前獲取信息的方法,主要獲取下載內容的大小,可以顯示下載進度多少字節

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders {

NSLog(@"didReceiveResponseHeaders-%@",[responseHeaders valueForKey:@"Content-Length"]);


    NSLog(@"contentlength=%f",request.contentLength/1024.0/1024.0);

    int bookid = [[request.userInfo objectForKey:@"bookID"] intValue];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    float tempConLen = [[userDefaults objectForKey:[NSString stringWithFormat:@"book_%d_contentLength",bookid]] floatValue];

    NSLog(@"tempConLen=%f",tempConLen);

    //如果沒有保存,則持久化他的內容大小

    if (tempConLen == 0 ) {//如果沒有保存,則持久化他的內容大小

        [userDefaults setObject:[NSNumber numberWithFloat:request.contentLength/1024.0/1024.0] forKey:[NSString stringWithFormat:@"book_%d_contentLength",bookid]];

    }


}

//ASIHTTPRequestDelegate,下載完成時,執行的方法

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

    

    int bookid = [[request.userInfo objectForKey:@"bookID"] intValue];

    CustomCell *cell = (CustomCell *)[self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:bookid inSection:0]];

    cell.downloadCompleteStatus = YES;

    cell.progressView.progress = 0.0; 

}


    經過上述步驟,一個支持斷點續傳的功能程序實現了!

發佈了4 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章