嘿!我需要知道如何让我的 iOS 应用程序在应用程序的后台开始下载(例如,在 AppDelegate 文件中运行下载),以便更改 ViewControllers 不会中断或取消下载。我还需要能够获取下载进度(0.00000 - 1.00000
),设置一个UIProgressView
对象,这也意味着我需要一个- (void)progressDidChangeTo:(int)progress
函数。
2 回答
只需使用ASIHTTPRequest它比 NSURLRequest 更容易,并且完全符合您的需要。它的示例显示了如何在后台下载以及如何报告进度。
我不会直接在 AppDelegate 中下载任何内容。相反,我会为此目的创建一个单独的类。我们称之为它MyService
,然后我将在我的应用程序委托中初始化该类。
该类可以作为单例工作,也可以传递给需要它的每个视图控制器。
在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];
顺便提一句。如果您需要在应用退出后继续下载,您可以将ShouldContinueWhenAppEntersBackground
请求的属性设置为“是”。
您可以使用 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
跟踪下载的数据量并计算百分比。
希望这会有所帮助,莫西