[英]iOS Application Background Downloading
嘿! 我需要知道如何讓我的iOS應用程序在應用程序的后台開始下載(比如,在AppDelegate文件中運行下載),因此更改ViewControllers不會中斷或取消下載。 我還需要能夠獲得下載的進度( 0.00000 - 1.00000
),將UIProgressView
對象設置為,這也意味着我需要一個- (void)progressDidChangeTo:(int)progress
函數。
只需使用ASIHTTPRequest它比NSURLRequest更容易,並完全滿足您的需求。 它的示例顯示了如何在后台下載以及如何報告進度。
我不會直接在AppDelegate中下載任何內容。 相反,我會為此目的創建一個單獨的類。 我們稱之為MyService
,然后在我的app delegate中初始化該類。
該類可以作為單例工作,也可以傳遞給需要它的每個視圖控制器。
在MyService
類中,我會添加ASINetworkQueue和幾個方法來處理准備好的請求。 以下是您可以使用的ASI示例代碼:
- (IBAction)startBackgroundDownloading:(id)sender
{
if (!self.queue) {
self.queue = [[[ASINetworkQueue alloc] init] autorelease];
}
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:@selector(requestDone:)];
[request setDidFailSelector:@selector(requestWentWrong:)];
[self.queue addOperation:request]; //queue is an NSOperationQueue
[self.queue go];
}
- (void)requestDone:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
//Do something useful with the content of that request.
}
- (void)requestWentWrong:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
如果需要設置進度條。 我只是在我的MyService類中公開ASINetworkQueue的setDownloadProgressDelegate,並在我的ViewControllers中設置它:
[[MyService service] setDownloadProgressDelegate: self.myUIProgressView];
BTW。 如果您需要在應用程序退出時繼續下載,可以將請求的ShouldContinueWhenAppEntersBackground
屬性設置為YES。
您可以使用NSURLConnection啟動異步請求,該請求不會導致您的UI被凍結。 您可以通過以下操作來完成:
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
[urlRequest release];
為了獲得進步,您可以使用:
connection:didReceiveResponse:(NSURLResponse *)response;
委托調用檢查response.expectedContentLength然后使用
connection:didReceiveData:(NSData *)data
跟蹤下載的數據量並計算百分比。
希望這有幫助,Moszi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.