【问题标题】:Continue download in background在后台继续下载
【发布时间】:2012-06-21 11:41:05
【问题描述】:

我正在创建一个应用程序,其中我正在从服务器下载一些数据。在后台运行时,我希望该连接应继续运行,以便可以下载数据。我知道 appDelegate 中有方法

- (void)applicationDidEnterBackground:(UIApplication *)application  

当应用程序进入后台时调用。但是由于连接是在viewController中创建的,那么如何在appDelegate中进行管理呢?
还有/还有其他方法可以做到吗?我已经浏览了this 链接,但是有什么简单的实现吗?

【问题讨论】:

标签: ios uiapplicationdelegate background-task


【解决方案1】:

[编辑] 抱歉,我不正确,正如 cmets 中指出的那样,您可以延长您必须在应用程序进入后台之前/之前执行操作的时间限制。这里是Apple's Official Documentation

【讨论】:

  • 这不是真的,你可以在后台执行Finite-Length task 最多10分钟。
  • @rckoenes 你确实是正确的,我很抱歉。我将编辑我的答案。感谢您的信息:)
  • 还是不行,可以在执行Finite-Length任务前调用beginBackgroundTaskWithExpirationHandler:。进入后台后,您无需执行这些操作。您可以在应用被推送到后台之前启动任务。
【解决方案2】:

我不知道您如何准确地处理数据下载。但是你可以看看ASIHTTPRequest。它非常简单明了,如果您将编译器标志设置为 -fno-objc-arc,它可以与 ARC 一起使用。有了这个,你只需要使用

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setShouldContinueWhenAppEntersBackground:YES]; //For iOS 4.0 and up 

这行得通。

Here你可以看到ASIHTTPRequest是如何工作的

希望对你有帮助!

【讨论】:

  • ASIHTTPRequest 不再积极开发...根据消息here。只是说。
  • 没错,但它仍然像一个魅力。我还没有找到任何功能与 ASIHTTPRequest 一样多的好选择。
【解决方案3】:

在后台继续执行某些操作的一种方法是创建一个单独的线程来进行下载。在线程内部,将您的下载操作括在对 beginBackgroundTaskWithExpirationHandler: 和 endBackgroundTask 的调用之间。你不需要检查你是否在后台运行,你总是调用这两个方法。

// Tell iOS this as a background task in case we get backgrounded
UIBackgroundTaskIdentifier taskId = [[UIApplication sharedApplication] 
          beginBackgroundTaskWithExpirationHandler:NULL];

//----------------------------------------------
// Perform your download operations here
//----------------------------------------------
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

// Tell iOS that we are done with stuff that needed to keep going even if backgrounded    
[[UIApplication sharedApplication] endBackgroundTask:taskId];

【讨论】:

  • 您可以设置 ASIHttpRequest 属性:[request setShouldContinueWhenAppEntersBackground:YES];
  • 非常感谢!!!如果我错了,请纠正我:总而言之,在后台或前台运行任务几乎没有区别。两者都将使用此代码执行。然而,我想到了两个不同之处:1. 如果您的后台任务太长,那么您可能会在完成之前被终止! 2. 最好endBackgroundTask:taskId 这样可以节省额外的电量。
猜你喜欢
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-05
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
  • 2012-04-30
相关资源
最近更新 更多