继续在后台下载

Nit*_*ish 12 uiapplicationdelegate ios background-task

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

- (void)applicationDidEnterBackground:(UIApplication *)application  
Run Code Online (Sandbox Code Playgroud)

当应用程序进入后台时调用.但是,随着连接的viewController中创建的,怎么能在管理的appDelegate
还有/其他方式可以这样做吗?我已经通过这个链接,但是有一些简单的实现吗?

pro*_*rmr 15

在后台继续执行某些操作的一种方法是创建一个单独的线程来进行下载.在线程内部,在对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];
Run Code Online (Sandbox Code Playgroud)