在后台IOS中执行长时间运行的任务

我一直在做一个应用程序,用户可以使用AVFoundation录制video并发送到服务器,video的最大尺寸可达15M,具体取决于networking的速度和types,大约需要1到5分钟的时间将video传输到服务器。 我正在后台线程中将录制的video传输到服务器,以便用户可以在video上传到服务器的同时在应用上继续播放其他内容。

在阅读Apple Docs以在后台执行长时间运行的任务时 ,我发现只有less数types的应用程序可以在后台执行。
例如

audio – 应用程序在后台播放可听内容给用户。 (此内容包括使用AirPlay播放audio或video内容。)

它是否符合我的应用程序还在后台运行任务? 或者我需要在主线程上传输video?

推荐使用NSOperationQueue来执行multithreading任务,以避免阻塞主线程。 后台线程用于在应用程序处于非活动状态时要执行的任务,如GPS指示或audiostream。

如果您的应用程序在前台运行,则根本不需要后台线程。

对于简单的任务,可以使用一个块将操作添加到队列中:

 NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init]; [operationQueue addOperationWithBlock:^{ // Perform long-running tasks without blocking main thread }]; 

有关NSOperationQueue的更多信息,以及如何使用它 。

上传过程将在后台继续,但您的应用程序将有资格被暂停,因此上传可能会被取消。 为了避免这种情况,您可以将以下代码添加到应用程序委托中,以便在应用程序准备好挂起时通知操作系统:

 - (void)applicationWillResignActive:(UIApplication *)application { bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ // Wait until the pending operations finish [operationQueue waitUntilAllOperationsAreFinished]; [application endBackgroundTask: bgTask]; bgTask = UIBackgroundTaskInvalid; }]; } 

从你对Dwayne的回应中,你不需要能够以后台模式下载。 相反,你需要的是在主线程旁边的另一个线程(后台线程)中进行下载。 像GCD这样的东西:

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Do you download here... }); 

您的要求有资格在后台运行。 您不需要注册info plist支持的任何背景模式。 所有你需要做的是,当应用程序即将进入后台,请求额外的时间使用后台任务处理程序,并在该块中执行您的任务。 确保您在10分钟之前停止您的处理程序,以免操作系统强制终止。

您可以使用Apple的下面的代码。

 - (void)applicationDidEnterBackground:(UIApplication *)application { bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ // Clean up any unfinished task business by marking where you // stopped or ending the task outright. [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Start the long-running task and return immediately. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Do the work associated with the task, preferably in chunks. [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; });}