2012-06-19 137 views
13

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

- (void)applicationDidEnterBackground:(UIApplication *)application 

当应用程序进入后台时调用。但由于连接是在viewController中创建的,因此如何管理appDelegate
也可以通过其他方式完成这项工作吗?我已经通过this链接,但有一个简单的实现?

+0

那就是做它的正式方法,THRE没有其他的方式,就像我知道 –

+0

你应该检查这个环节http://stackoverflow.com/questions/4579810/ios-application-background-downloading – swiftBoy

回答

14

做一些在后台继续的操作的一种方法是创建一个单独的线程来执行下载。在线程内部,在调用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]; 
+1

您可以设置ASIHttpRequest属性:[request setShouldContinueWhenAppEntersBackground:YES]; – HelloWorld

+0

非常感谢你!如果我错了,请纠正我:总之,在后台或前台运行任务几乎没有区别。两者都将使用此代码执行。但是有两点不同:1。**如果**你的后台任务太长,那么在完成之前你可能会被终止! 2.最好'endBackgroundTask:taskId',这样可以节省额外的电池。 – Honey

4

对不起,我是不正确的,正如在评论中指出的,你可以延长时间限制,你必须执行一次操作/在你的应用程序进入后台之前。这里是Apple's Official Documentation

+0

这是不正确的,你可以执行[有限长度任务](http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/ doc/uid/TP40007072-CH4-SW28)最多10分钟。 – rckoenes

+0

@rckoenes你确实是对的,我的道歉。我会编辑我的答案。感谢您的信息:) – bennythemink

+0

仍然不是真的,你可以调用['beginBackgroundTaskWithExpirationHandler:'](http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html# //执行Finite-Length任务之前,请先执行Apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithExpirationHandler :)。一旦你进入后台,你不需要执行操作。您可以在将应用推送到后台之前开始执行任务。 – rckoenes

1

我不知道你如何处理你的数据下载。但你可以看看ASIHTTPRequest。它非常简单直接,如果将编译器标志设置为-fno-objc-arc,则适用于ARC。有了这个你只需要使用

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

而且工作。

Here你可以看到ASIHTTPRequest如何工作

希望它能帮助!

+0

ASIHTTPRequest不再积极开发......按照每条消息[here](http://allseeing-i.com/ASIHTTPRequest/)。只是说。 – zero0cool

+0

的确如此,但它仍然像魅力一样。我还没有找到任何具有与ASIHTTPRequest一样多的功能的好选择。 – Thermometer