標籤:
1.匯入ASIHTTPRequest第三方類庫
:ASIHttpRequest類庫 完整代碼下載:下載
2.在 .h 檔案中
[cpp] view plaincopy
- #import <UIKit/UIKit.h>
- #import "ASIHTTPRequest.h"
- #import "ASINetworkQueue.h"
- @interface DownLoadViewController : UIViewController<ASIHTTPRequestDelegate>
- {
- UIProgressView *_progressView;
- }
-
- @property(nonatomic, retain) UIProgressView *progressView;
- @property(nonatomic, retain) ASINetworkQueue *asiQueue;
- @property(nonatomic, retain) ASIHTTPRequest *asiHttpRequest;
- @end
3.在 .m 檔案中 實現這一過程
首先開啟隊列:
[cpp] view plaincopy
- _asiQueue=[[ASINetworkQueue alloc]init];//開啟隊列
- [_asiQueue reset];//nil
- _asiQueue.showAccurateProgress=YES;//進度
- [_asiQueue go];
實現下載:
[cpp] view plaincopy
- NSURL *url = [NSURL URLWithString:@"請求地址"];
-
- _asiHttpRequest=[ASIHTTPRequest requestWithURL:url];
- _asiHttpRequest.delegate=self;
- _asiHttpRequest.downloadProgressDelegate=self;//下載進度的代理,用於斷點續傳
-
-
- path = NSHomeDirectory();//該方法得到的是應用程式目錄的路徑
-
- //目的路徑,設定一個目的路徑用來儲存下載下來的檔案
- NSString *savePath = [path stringByAppendingPathComponent:@"qgw.mp3"];
- /*
- 臨時路徑:
- 1.設定一個臨時路徑用來儲存下載過程中的檔案
- 2.當下載完後會把這個檔案拷貝到目的路徑中,並刪除臨時路徑中的檔案
- 3.斷點續傳:當設定斷點續傳的屬性為YES後,每次執行都會到臨時路徑中尋找要下載的檔案是否存在,下載的進度等等。。。然後就會在此基礎上繼續下載,從而實現續傳的效果
- 設定臨時路徑在這個過程中是相當重要的。。。
- */
- NSString *temp = [path stringByAppendingPathComponent:@"temp"];
-
- /*
- 又在臨時路徑中添加了一個mp3格式的檔案,這就相當於設定了一個假的要下載的檔案,其實是不存在的,可以這麼理解:這裡提供了一個容器,下載的內容填充到了這個容器中。
- 這個容器是必須要設定的,要不然它會不知道要下載到什麼裡面。。。
-
- 會有人說:問什麼不和上面的臨時路徑拚在一起,不是一樣麼:NSString *temp = [path stringByAppendingPathComponent:@"temp/qgw.mp3"];
- 這是不行的,因為你的臨時路徑必須要保證是正確的、是擁有的,所以在下面你要用NSFileManager來判斷是否存在這麼一個路徑,如果不存在就去建立,
- 當你建立的時候會把qgw.mp3當作是一個檔案夾來建立的,所以每次斷點續傳的時候都會進入到qgw.mp3這個檔案夾中尋找,當然是找不到的(因為qwg.mp3就是)
- so,要分開來寫。。。
-
- */
- NSString *tempPath = [temp stringByAppendingPathComponent:@"qgw.mp3"];
-
- //建立檔案管理工具
- NSFileManager *fileManager = [NSFileManager defaultManager];
- //判斷temp檔案夾是否存在
- BOOL fileExists = [fileManager fileExistsAtPath:temp];
- if (!fileExists)
- {//如果不存在則建立,因為下載時,不會自動建立檔案夾
-
- [fileManager createDirectoryAtPath:temp
- withIntermediateDirectories:YES
- attributes:nil
- error:nil];
- }
-
- [ _asiHttpRequest setDownloadDestinationPath:savePath ];//下載路徑
- [ _asiHttpRequest setTemporaryFileDownloadPath:tempPath ];//臨時路徑,一定要設定臨時路徑。。
-
- _asiHttpRequest.allowResumeForFileDownloads = YES;//開啟斷點,是否要斷點續傳
-
- //進度條
- _progressView.alpha = 1.0f;
- _progressView.progress=0;//賦值為0
-
- [_asiQueue addOperation:_asiHttpRequest];//排入佇列
得到下載的進度:
[cpp] view plaincopy
- //代理方法,得到下載進度
- - (void)setProgress:(float)newProgress{
- [_progressView setProgress:newProgress];//賦給進度條
- }
停止下載:
[cpp] view plaincopy
- [_asiHttpRequest clearDelegatesAndCancel];//停掉
IOS成長之路-ASIHTTPRequest 斷點續傳