来源
Setup background task.
This is needed because the capture(_:, didFinishRecordingToOutputFileAt:, fromConnections:, error:)
callback is not received until AVCam returns to the foreground unless you request background execution time.This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded.To conclude this background execution, endBackgroundTask(_:) is called incapture(_:, didFinishRecordingToOutputFileAt:, fromConnections:, error:)
after the recorded file has been saved.
翻译
设置后台任务.
在后台你是接收不到capture(_:, didFinishRecordingToOutputFileAt:, fromConnections:, error:)
这个方法的回调的,除非你请求了后台执行时间.有了后台执行时间,这个也确保了程序在后台时有时间去保存文件到相册里.要结束后台的执行,你要在capture(_:, didFinishRecordingToOutputFileAt:, fromConnections:, error:)
回调里保存文件后调用endBackgroundTask(_:)
.
private var backgroundRecordingID: UIBackgroundTaskIdentifier? = nil
@IBAction private func toggleMovieRecording(_ recordButton: UIButton) {
guard let movieFileOutput = self.movieFileOutput else {
return
}
/*
Disable the Camera button until recording finishes, and disable
the Record button until recording starts or finishes.
See the AVCaptureFileOutputRecordingDelegate methods.
*/
cameraButton.isEnabled = false
recordButton.isEnabled = false
captureModeControl.isEnabled = false
/*
Retrieve the video preview layer's video orientation on the main queue
before entering the session queue. We do this to ensure UI elements are
accessed on the main thread and session configuration is done on the session queue.
*/
let videoPreviewLayerOrientation = previewView.videoPreviewLayer.connection.videoOrientation
sessionQueue.async { [unowned self] in
if !movieFileOutput.isRecording {
if UIDevice.current.isMultitaskingSupported {
/*
Setup background task.
This is needed because the `capture(_:, didFinishRecordingToOutputFileAt:, fromConnections:, error:)`
callback is not received until AVCam returns to the foreground unless you request background execution time.
This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded.
To conclude this background execution, endBackgroundTask(_:) is called in
`capture(_:, didFinishRecordingToOutputFileAt:, fromConnections:, error:)` after the recorded file has been saved.
*/
self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
}
// Update the orientation on the movie file output video connection before starting recording.
let movieFileOutputConnection = self.movieFileOutput?.connection(withMediaType: AVMediaTypeVideo)
movieFileOutputConnection?.videoOrientation = videoPreviewLayerOrientation
// Start recording to a temporary file.
let outputFileName = NSUUID().uuidString
let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent((outputFileName as NSString).appendingPathExtension("mov")!)
movieFileOutput.startRecording(toOutputFileURL: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)
}
else {
movieFileOutput.stopRecording()
}
}
}
func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
/*
Note that currentBackgroundRecordingID is used to end the background task
associated with this recording. This allows a new recording to be started,
associated with a new UIBackgroundTaskIdentifier, once the movie file output's
`isRecording` property is back to false — which happens sometime after this method
returns.
Note: Since we use a unique file path for each recording, a new recording will
not overwrite a recording currently being saved.
*/
func cleanup() {
let path = outputFileURL.path
if FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.removeItem(atPath: path)
}
catch {
print("Could not remove file at url: \(outputFileURL)")
}
}
if let currentBackgroundRecordingID = backgroundRecordingID {
backgroundRecordingID = UIBackgroundTaskInvalid
if currentBackgroundRecordingID != UIBackgroundTaskInvalid {
UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)
}
}
}
var success = true
if error != nil {
print("Movie file finishing error: \(error)")
success = (((error as NSError).userInfo[AVErrorRecordingSuccessfullyFinishedKey] as AnyObject).boolValue)!
}
if success {
// Check authorization status.
PHPhotoLibrary.requestAuthorization { status in
if status == .authorized {
// Save the movie file to the photo library and cleanup.
PHPhotoLibrary.shared().performChanges({
let options = PHAssetResourceCreationOptions()
options.shouldMoveFile = true
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: .video, fileURL: outputFileURL, options: options)
}, completionHandler: { success, error in
if !success {
print("Could not save movie to photo library: \(error)")
}
cleanup()
}
)
}
else {
cleanup()
}
}
}
else {
cleanup()
}
// Enable the Camera and Record buttons to let the user switch camera and start another recording.
DispatchQueue.main.async { [unowned self] in
// Only enable the ability to change camera if the device has more than one camera.
self.cameraButton.isEnabled = self.videoDeviceDiscoverySession.uniqueDevicePositionsCount() > 1
self.recordButton.isEnabled = true
self.captureModeControl.isEnabled = true
self.recordButton.setTitle(NSLocalizedString("Record", comment: "Recording button record title"), for: [])
}
}