Kavi Ramamurthy Kavi Ramamurthy - 1 year ago 289
Swift Question

How to add autofocus to AVCaptureSession? SWIFT

I'm using AVFoundation to recognize text and perform OCR. How do I add autofocus? I don't want to have the yellow square thing when user taps the screen, I just want it to automatically focus on the object, a credit card for example.

Here is my session code.

func setupSession() {
session = AVCaptureSession()
session.sessionPreset = AVCaptureSessionPresetHigh

let camera = AVCaptureDevice

do { input = try AVCaptureDeviceInput(device: camera) } catch { return }

output = AVCaptureStillImageOutput()
output.outputSettings = [ AVVideoCodecKey: AVVideoCodecJPEG ]

guard session.canAddInput(input)
&& session.canAddOutput(output) else { return }


previewLayer = AVCaptureVideoPreviewLayer(session: session)

previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer!.connection?.videoOrientation = .Portrait




Answer Source

On my 6S the default camera focus mode is .ContinuousAutoFocus, which continuously focuses on whatever is taking up most of the camera's field of vision. Sounds like that's what you want.

You can check if your camera supports auto focus like so:


and if it's not already set, set it like so:

try! camera.lockForConfiguration()
camera.focusMode = .ContinuousAutoFocus
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download