ios – didFinishProcessingPhotoSampleBuffer没有调用

我正在尝试学习如何使用AVFoundation拍摄和保存照片.我目前能够使用一个链接到拍摄动作的按钮来制作自定义相机视图.当我单击按钮时,没有调用委托方法.

这是我的ViewController.swift

class ViewController: UIViewController, AVCapturePhotoCaptureDelegate{

    @IBOutlet weak var camerView: UIView!
    @IBOutlet weak var photoButton: UIButton!

    var captureSession : AVCaptureSession?
    var sessionOutput : AVCapturePhotoOutput?
    var previewLayer : AVCaptureVideoPreviewLayer?

    var photoSettings : AVCapturePhotoSettings?

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        previewLayer?.frame = (self.camerView?.bounds)!
        previewLayer?.position = CGPoint(x: (self.camerView?.frame.width)! / 2, y: (self.camerView?.frame.height)!/2)

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        //Capture Session 
        captureSession = AVCaptureSession()

        let devices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInDualCamera], mediaType: AVMediaTypeVideo, position: .back)

        for device in (devices?.devices)! {

            do {
                let input = try AVCaptureDeviceInput(device: device)

                if (captureSession?.canAddInput(input))! {
                    captureSession?.addInput(input)
                }
                if (captureSession?.canAddOutput(sessionOutput))! {
                    captureSession?.addOutput(sessionOutput)
                }

                previewLayer = AVCaptureVideoPreviewLayer()

                previewLayer?.session = captureSession

                self.camerView.layer.addSublayer(previewLayer!)
                self.camerView.addSubview(photoButton)

                captureSession?.startRunning()

            } catch {
                print("error occurred")
            }

        }


    }

    @IBAction func takePhoto(_ sender: UIButton) {

        photoSettings = AVCapturePhotoSettings(format: [AVVideoCodecKey : AVVideoCodecJPEG])
        photoSettings?.flashMode = .on
        sessionOutput?.capturePhoto(with: photoSettings!, delegate: self)


    }


    //AVCapturePhotoCaptureDelegate Functions

    func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
        print("PhotoSampleBuffer")
    }




}

我想在didFinisheProcessingPhotoSampleBuffer方法中做的只是print(),所以我知道它正被调用.我将弄清楚如何保存以后(除非有人能指出我很好的资源来学习这个.)

如果您需要任何其他信息,请告诉我们!

最佳答案 由于sessionOutput变量为nil,因此未调用capturePhoto方法(以及委托回调).

要解决此问题,请在声明sessionOutput变量时将其实例化:

var sessionOutput = AVCapturePhotoOutput()

另外,你需要删除? sessionOutput之后,因为它不再是可选的.

sessionOutput.capturePhoto(with: photoSettings!, delegate: self)
点赞