Turning AutoFocus off while flash is on.

Hello, I am creating a simple camere app where I want to turn OFF the autofocus (and set the focus within the app) then take a picture with the flash. The only problem is as soon as i set the flash and take a photo, it auto focuses even though i have set the focus mode locked and lens position? Is this even possible?

My av capture output settings:

    photoOutput.isHighResolutionCaptureEnabled = true
    photoOutput.isLivePhotoCaptureEnabled = false;
    photoOutput.isDepthDataDeliveryEnabled = false;
    photoOutput.isPortraitEffectsMatteDeliveryEnabled = false
    photoOutput.isAppleProRAWEnabled = false;
    photoOutput.setPreparedPhotoSettingsArray([buildPhotoSettings(flash: flash)]);

my AVCapturePhoto Settings

    let photoSettings = AVCapturePhotoSettings(rawPixelFormatType: availbleRaw[0]);
    photoSettings.isAutoStillImageStabilizationEnabled = false;
    photoSettings.flashMode = flash ?.on :.off;
    photoSettings.isHighResolutionPhotoEnabled = true;
    photoSettings.isAutoRedEyeReductionEnabled = false;

my device input settings

     
    //--white balance
    let whiteBalanceValues = AVCaptureDevice.WhiteBalanceTemperatureAndTintValues(temperature: settings.whiteBalanceTemp, tint: settings.whiteBalanceTint);
    let newWhiteBalance = videoDeviceInput.device.deviceWhiteBalanceGains(for:whiteBalanceValues);
    let maxGain = videoDeviceInput.device.maxWhiteBalanceGain
     
    if(newWhiteBalance.redGain > maxGain || newWhiteBalance.greenGain > maxGain || newWhiteBalance.blueGain > maxGain){
      videoDeviceInput.device.unlockForConfiguration();
      return (false, "WhiteBalance values are invalid (over maximum gain allowed)");
    }
     
    videoDeviceInput.device.setWhiteBalanceModeLocked(with: newWhiteBalance);
     
    //--iso and exposure
    let exposure = Float64(settings.exposure/1000);
    let exposureTime = CMTime(seconds: exposure, preferredTimescale: 1000)
    let iso = Float(settings.iso)
     
    if(exposureTime > videoDeviceInput.device.activeFormat.maxExposureDuration || exposureTime < videoDeviceInput.device.activeFormat.minExposureDuration){
      videoDeviceInput.device.unlockForConfiguration();
      return (false, "Exposure out of bounds");
    }
     
    if(iso > videoDeviceInput.device.activeFormat.maxISO || iso < videoDeviceInput.device.activeFormat.minISO){
      videoDeviceInput.device.unlockForConfiguration();
      return (false, "ISO out of bounds");
    }
     
    videoDeviceInput.device.setExposureModeCustom(duration: exposureTime, iso: iso);
     
    //--Lens focus
    if(settings.lensPosition < 0 || settings.lensPosition>1){
      videoDeviceInput.device.unlockForConfiguration();
      return (false, "Lens position out of bounds");
    }
     
   
    if(videoDeviceInput.device.isFocusModeSupported(.locked)){
      videoDeviceInput.device.focusMode = .locked;
      videoDeviceInput.device.setFocusModeLocked(lensPosition: settings.lensPosition);
       
    }
     
    if #available(iOS 15.4, *) {
      if(videoDeviceInput.device.isFaceDrivenAutoFocusEnabled){
        videoDeviceInput.device.automaticallyAdjustsFaceDrivenAutoFocusEnabled = false;
         
      }
       
      if(videoDeviceInput.device.isFaceDrivenAutoExposureEnabled){
        videoDeviceInput.device.automaticallyAdjustsFaceDrivenAutoExposureEnabled = false;

      }
       
      if(videoDeviceInput.device.isLowLightBoostSupported){
        videoDeviceInput.device.automaticallyEnablesLowLightBoostWhenAvailable = false;

      }
    } else {
      // Fallback on earlier versions
    }
     
    //--Torch ON
    videoDeviceInput.device.torchMode = settings.torch ? AVCaptureDevice.TorchMode.on :AVCaptureDevice.TorchMode.off;
     
    if(settings.torch){
      if(settings.torchLevel<0 || settings.torchLevel>1){
        return (false, "Flash out of bounds");
      }
       
      try? videoDeviceInput.device.setTorchModeOn(level: Float(settings.torchLevel));
    }
     
     
     
    //--Finish
    videoDeviceInput.device.unlockForConfiguration();

The only problem is as soon as i set the flash and take a photo, it auto focuses even though i have set the focus mode locked and lens position? Is this even possible?

I've confirmed this is possible in a test app (I successfully locked the lensPosition and took a photo with the flash on, autofocus never came back on).

It is conceivable that there may be something about your configuration causing this (though I'm not sure what that would be), I think most likely it is something in your code that is re-enabling auto-focus.

I recommend that you create a new focused sample project that does nothing other than capture with locked focus and flash enabled. If you can't reproduce the issue there, then start adding in pieces of your larger project until the issue returns.

It may also be helpful to add some logging to your app whenever you set the focusMode of a device.

Hello, here is my example. I am testing on an iPhone 14 pro on ios 16.3. I still cannot get it to stop autofocusing.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var captureSession: AVCaptureSession!
    var previewLayer: AVCaptureVideoPreviewLayer!
    var photoOutput: AVCapturePhotoOutput!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupCamera()
        setupCaptureButton()
    }
    
    func setupCamera() {
        captureSession = AVCaptureSession()
        captureSession.sessionPreset = .photo
        
        guard let device = AVCaptureDevice.default(for: .video) else { return }
        
        do {
            let input = try AVCaptureDeviceInput(device: device)
            
            if captureSession.canAddInput(input) {
                captureSession.addInput(input)
            }
            
            try device.lockForConfiguration()
            
            device.isSubjectAreaChangeMonitoringEnabled = false
            device.exposureMode = .locked
            device.setFocusModeLocked(lensPosition: 0.1);

            device.unlockForConfiguration()

            photoOutput = AVCapturePhotoOutput()
            if captureSession.canAddOutput(photoOutput) {
                captureSession.addOutput(photoOutput)
            }
            
            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            previewLayer.frame = view.layer.bounds
            previewLayer.videoGravity = .resizeAspectFill
            view.layer.addSublayer(previewLayer)
            
            DispatchQueue.global(qos: .default).async {
                self.captureSession.startRunning()
            }
        } catch {
            print("Error setting up camera: \(error)")
        }
    }
    
    @objc func takePhoto() {
        let rawPixelFormats=photoOutput.availableRawPhotoPixelFormatTypes;
        let settings = AVCapturePhotoSettings(rawPixelFormatType: rawPixelFormats[0]);
        
        settings.flashMode = .on
        settings.isAutoRedEyeReductionEnabled = false;
        settings.isAutoVirtualDeviceFusionEnabled = false;
        settings.isPortraitEffectsMatteDeliveryEnabled=false;
        settings.isAutoContentAwareDistortionCorrectionEnabled=false;
        settings.isDepthDataDeliveryEnabled=false;
        settings.embedsDepthDataInPhoto=false;
        settings.isDepthDataFiltered = false;
        settings.embedsSemanticSegmentationMattesInPhoto = false;
        settings.embedsPortraitEffectsMatteInPhoto = false;
        
        photoOutput.capturePhoto(with: settings, delegate: self)
    }
    
    func setupCaptureButton() {
        let captureButton = UIButton(frame: CGRect(x: view.center.x - 50, y: view.bounds.maxY - 120, width: 100, height: 100))
        captureButton.backgroundColor = .white
        captureButton.layer.cornerRadius = 50
        captureButton.addTarget(self, action: #selector(takePhoto), for: .touchUpInside)
        view.addSubview(captureButton)
    }
}

extension ViewController: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let error = error {
            print("Error capturing photo: \(error)")
        } else {
            if let imageData = photo.fileDataRepresentation(), let image = UIImage(data: imageData) {
                &#x2F;&#x2F;UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            }
        }
    }
}
Turning AutoFocus off while flash is on.
 
 
Q