AVFoundation 后台回调

来源

https://developer.apple.com/library/content/samplecode/AVCam/Listings/Swift_AVCam_CameraViewController_swift.html#//apple_ref/doc/uid/DTS40010112-Swift_AVCam_CameraViewController_swift-DontLinkElementID_15

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: [])
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一直以来,喜欢憧憬未来,对美好生活的向往是我前进的最大动力。我憧憬一切美好的事物,我憧憬事业上的成功,希望有一天能...
    吾先生ING阅读 320评论 2 0
  • 我在文友的诗里看到一张图,一士兵在林子里弹琴,忽然觉得这图中士兵的情怀很似我! 原本我把今日写的这段文字叫:我的早...
    小墉正阅读 1,345评论 74 102
  • 我很想知道,你要给我的幸福是什么样子。或许是陪伴,是一个家的温暖,当我幻想幸福即将启航,它充满未知的道路,我们是否...
    一清水阅读 405评论 0 0