Search code examples
iosswiftcameraavfoundationavcapturesession

AVCapturePhotoOutput - settings may not be reused


I am running ios 12 swift 4.2.

I have implemented a basic camera capture session and am clicking images from it. Everything is fine until I am toggling the flash between auto/on/off mode. After I click the first photo and then change the flash mode, the app crashes with error :

[AVCapturePhotoOutput capturePhotoWithSettings:delegate:] Settings may not be re-used'

Following is the camera implementation:

var captureSession: AVCaptureSession!
var videoPreviewLayer: AVCaptureVideoPreviewLayer!
var capturePhotoOutput: AVCapturePhotoOutput!
let capturePhotoSettings = AVCapturePhotoSettings()


var previewView: UIView!


override func viewDidLoad() {
    startCameraSession()
    setupCaptureOutput()
}

@objc // Tap on a button to capture
func takePhotoOnTap() {
    guard let capturePhotoOutput = self.capturePhotoOutput else { return }

    capturePhotoSettings.isAutoStillImageStabilizationEnabled = true
    capturePhotoSettings.isHighResolutionPhotoEnabled = true
    capturePhotoSettings.flashMode = .auto
    let _ = getSettings(camera: captureDevice!, flashMode: spotmiCameraOptions.flashMode)
    capturePhotoOutput.capturePhoto(with: capturePhotoSettings, delegate: self)
}


    //This is a delegate method from the button
func toggleFlash(mode: FlashMode) {

    switch mode {
    case .auto:
        capturePhotoSettings.flashMode = .auto
    case .enabled:
        capturePhotoSettings.flashMode = .on
    case .disabled:
        capturePhotoSettings.flashMode = .off
    }

}


func setupCaptureOutput() {
    capturePhotoOutput = AVCapturePhotoOutput()
    capturePhotoOutput.isHighResolutionCaptureEnabled = true
    captureSession.addOutput(capturePhotoOutput)
}

func startCameraSession() {

    let captureDevice = AVCaptureDevice.default(.builtInDualCamera, for: AVMediaType.video, position: .back)

    do {
        let input = try AVCaptureDeviceInput(device: captureDevice!)
        captureSession = AVCaptureSession()
        captureSession.addInput(input)
        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        videoPreviewLayer.videoGravity = .resizeAspectFill
        videoPreviewLayer.frame = self.view.layer.bounds
        camcontainer.layer.addSublayer(videoPreviewLayer)
        captureSession.startRunning()
    } catch {
        print(error.localizedDescription)
    }


}

func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
    guard error == nil, let sampleBuffer = photoSampleBuffer else {
        print("error capturing photo due to \(String(describing: error?.localizedDescription))")
        return
    }
    guard let imageData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer) else  { return }

    let capturedImage = UIImage(data: imageData, scale: 1.0)
    if let image = capturedImage {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    }
}

    func getSettings(camera: AVCaptureDevice, flashMode: FlashMode) -> AVCapturePhotoSettings {
    let settings = capturePhotoSettings

    if camera.hasFlash {
        switch flashMode {
//            case .auto: settings.flashMode = .auto
        case .enabled: settings.flashMode = .on
        case .disabled: settings.flashMode = .off
        default: settings.flashMode = .auto
        }
    }
    return settings
}

I am really not getting my head around on how to exactly reuse the captureSettings and change it everytime with a different flash mode. I am gone through couple of questions but they are majorly about torch lights. I am looking for the flash .

Any help is very much appreciated.


Solution

  • AVCapturePhotoSettings object is unique and cannot be reused, so you need to get new settings every time using this method:

    func getSettings(camera: AVCaptureDevice, flashMode: CurrentFlashMode) -> AVCapturePhotoSettings {
        let settings = AVCapturePhotoSettings()
    
        if camera.hasFlash {
            switch flashMode {
               case .auto: settings.flashMode = .auto
               case .on: settings.flashMode = .on
               default: settings.flashMode = .off
            }
        }
        return settings
    }
    

    As you can see, lockConfiguration is not needed.

    CurrentFlashMode is enum, which has been created to keep things clear:

    enum CurrentFlashMode { case off case on case auto }

    Then simply use it while capturing photo:

     @IBAction func captureButtonPressed(_ sender: UIButton) {
            let currentSettings = getSettings(camera: currentCamera, flashMode: currentFlashMode)
            photoOutput.capturePhoto(with: currentSettings, delegate: self)
        }