iPhone Recording: Resume after Background

A reader asks if it is possible to adapt this sample (demonstrating pausing and resuming iPhone video recording) so that it can resume when the app returns from the background.

The short answer is that (as far as I can see) it is possible, but fiddly.

The AVFoundation asset writer does not have the option to append to an existing file. So if you want to resume recording to the same file, you’ll need to keep that open while in the background. The MP4 file format has an index that is written out to the file at the end of recording. Without this index, it is not possible to play the file. So if you leave the file open, it is not playable at all, and if you close it, you cannot write any more to it.

The asset writer is writing to the file in the background. So when your app is sent to the background, even if you terminate the camera session, there will still be data to write and these writes will be terminated, causing an error. There’s no simple way to wait for the background writes to complete, unless you close the whole file. So option 1 is to request background time and just keep the app active in the background. To be honest, this seems very unsatisfactory.

The only other alternative is to start a new file, and combine it with the old file. You could either write the old file to the new file before resuming recording (but that makes resuming a very slow operation) or you could create a different file each time and combine them when you stop recording (but that makes stopping recording a slow operation).

My suggestion is this: - before suspending, you are recording to a file (file A) which you close on entering background. - when you resume, start recording to a new file (file B). - in the background, create a new file C. - write everything from file A to file C and delete file A. - read the data from file B as it is being written, using this sample, and write to file C.

I think whatever the approach you take, you will need to copy all the recorded data after resuming. If you write a separate file each time and combine all the files at the end, you only need to do this copy once, but it will be potentially a slow operation. This approach copies all the data every time you resume, but it does it in the background and should make both resuming and finishing rapid.

For the time being, I’ll leave this as an exercise to the reader.

22nd March 2013