5

I've been looking for the answer for 2 days, but I can't seem to get it right...

I have an example app that records audio and video from the device using a AVCaptureSession and a AVCaptureMovieFileOutput.

When I start recording I call:

[self.movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];

And it starts recording to the file. If I press the button again it stops recording

[self.movieFileOutput stopRecording];

Everything works well, but when I enter background (incoming call or HOME press) I get an error in the delegate method: didFinishRecordingToOutputFileAtURL

My desired action should be saving / completing the file on entering the background. If I call stopRecording on "applicationDidEnterBackground" it will enter background before the applicationDidEnterBackground is called. On entering the active state it is called.... and generates an error and leaves a corrupted movie file...

It seems that it hasn't got enough time to save the file.

What am I missing here?

This is my Error

Error Domain=AVFoundationErrorDomain Code=-11818 "Recording Stopped" UserInfo=0x17594e20 {NSLocalizedRecoverySuggestion=Stop any other actions using the recording device and try again., NSUnderlyingError=0x175d3500 "The operation couldn’t be completed. (OSStatus error -16133.)", NSLocalizedDescription=Recording Stopped}

AVErrorSessionWasInterrupted = -11818
4

2 回答 2

3

NSOperationQueue是执行多线程任务以避免阻塞主线程的推荐方式。后台线程用于您希望在应用程序处于非活动状态时执行的任务,例如 GPS 指示或音频流。

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

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

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;
    }]; 
}
于 2013-12-16T12:40:20.567 回答
1

您可以处理保存,applicationWillResignActive:然后您可以在后台继续您的过程。

于 2013-12-16T13:04:40.230 回答