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

我一直在使用一个应用程序,用户可以使用AVFoundation录制视频并发送到服务器,视频的最大大小可达15M,具体取决于互联网速度和速度.输入时间大约可能需要1到5分钟才能将视频传输到服务器.我将录制的视频传输到后台线程中的服务器,以便用户可以在视频上传到服务器时继续其他应用程序.

在阅读Apple Docs for implementing long running tasks in backround时,我看到只有几种应用可以在后台执行.
例如

audio—The app plays audible content to the user while in the background. (This content includes streaming audio or video content using AirPlay.)

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

解决方法

NSOperationQueue是执行多线程任务以避免阻塞主线程的推荐方法.背景线程用于您的应用程序处于非活动状态时要执行的任务,如GPS指示或音频流.

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

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

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

更多关于NSOperationQueuehow to use it的信息.

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

- (void)applicationWillResignActive:(UIApplication *)application {
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{

      // Wait until the pending operations finish
      [operationQueue waitUntilAllOperationsAreFinished];

      [application endBackgroundTask: bgTask];
      bgTask = uibackgroundtaskInvalid;
    }]; 
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...