swiftxcodeavfoundationavcapturesessionibaction

Swift If you specify a non-nil format dictionary in your settings, your delegate must respond to the selector captureOutput:didFinishProcessingPhoto


The code I am using below is supposed to take a photo and then convert the image to base64 in order to send it to a server. The code worked taking the photo, converting it to base64, and uploading it to my server but has stopped working. I have tried using other stack overflow posts to solve this issue but it has not worked for me. Thanks for any responses in advance!

Error

Thread 1: Exception: "*** -[AVCapturePhotoOutput capturePhotoWithSettings:delegate:] If you specify a non-nil format dictionary in your settings, your delegate must respond to the selector captureOutput:didFinishProcessingPhoto:error:, or the deprecated captureOutput:didFinishProcessingPhotoSampleBuffer:previewPhotoSampleBuffer:resolvedSettings:bracketSettings:error:"

Code:

@IBAction func takePhotoButtonPressed(_ sender: Any) {
      let settings = AVCapturePhotoSettings()
      let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first!
      let previewFormat = [kCVPixelBufferPixelFormatTypeKey as String: previewPixelType,
                           kCVPixelBufferWidthKey as String: 160,
                           kCVPixelBufferHeightKey as String: 160]
      settings.previewPhotoFormat = previewFormat
      sessionOutput.capturePhoto(with: settings, delegate: self)
}
        

func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
    let imageData = photo.fileDataRepresentation()
    let base64String = imageData?.base64EncodedString()
    print(base64String!)
}

Solution

  • Let's break down the error message:

    So in all, whatever the type of self is, you need to make sure it implements the method photoOutput(_:didFinishProcessingPhoto:error:)