在后台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;
    }]; 
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...