嘿!我需要知道如何让iOS应用程序在应用程序的背景下启动下载(例如,在AppDelegate文件中运行下载),因此更改ViewControllers不会中断或取消下载。我还需要能够获得下载的进度(0.00000 - 1.00000),设置一个 UIProgressView 反对,这也意味着我需要一个 - (void)progressDidChangeTo:(int)progress 功能。

有帮助吗?

解决方案

只是使用 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 您的请求的属性为Yes。

其他提示

您可以使用nsurlconnection启动异步请求,这不会导致UI被冷冻。您可以通过做类似的操作来做到这一点:

NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
[urlRequest release];

为了取得进展,您可以使用:

connection:didReceiveResponse:(NSURLResponse *)response;

委托呼叫检查响应。预计contentlength,然后使用

connection:didReceiveData:(NSData *)data

跟踪下载的数据量并计算一个百分比。

希望这会有所帮助,Moszi

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top