【问题标题】:iOS Application Background DownloadingiOS应用后台下载
【发布时间】:2011-06-02 13:30:39
【问题描述】:

嘿!我需要知道如何让我的 iOS 应用程序在应用程序的后台开始下载(例如,在 AppDelegate 文件中运行下载),以便更改 ViewControllers 不会中断或取消下载。我还需要能够获取下载进度(0.00000 - 1.00000),设置一个UIProgressView对象,这也意味着我需要一个- (void)progressDidChangeTo:(int)progress函数。

【问题讨论】:

    标签: iphone download uiapplicationdelegate download-manager


    【解决方案1】:

    只需使用ASIHTTPRequest,它比 NSURLRequest 简单得多,并且完全符合您的需要。 它examples 显示如何在后台下载以及如何报告进度。

    我不会直接在 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。

    【讨论】:

    • ...我是。我需要在 AppDelegate 文件中进行下载,以便在启动它的 UIViewController 启动时下载不会停止。我需要知道如何让 UIViewController 启动和访问 ASIHTTPRequest 对象,但将对象保存在 AppDelegate 中。
    • 问题是每次我的应用从后台返回时都会在 ASIHTTPRequest.m 中调用 reportFailure。我使用的方式与您在帖子中建议的方式相同,并且应该将 ShouldContineWhenAppEntersBackground 设置为 YES。
    【解决方案2】:

    您可以使用 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
    

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

    希望这会有所帮助, 莫西

    【讨论】:

    • 我把下载部分下来了,使用ASIHTTPRequest,我只需要知道如何实现下载在后台启动,而不是当前打开的UIViewController,所以当view controller被dismiss时,下载继续。
    • 你可以创建一个单例类来管理你的下载,这样即使你的视图控制器被释放了,这个类也会存在。 (维基百科上的单例模式:en.wikipedia.org/wiki/Singleton_pattern
    猜你喜欢
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2018-07-10
    • 2014-05-07
    • 2021-03-03
    相关资源
    最近更新 更多