Search code examples
iosxcodeswiftcameraavfoundation

Set Camera Focus On Tap Point With Swift


The API for using the camera in swift seems a but different and I am having a hard time focusing the camera on a point. When the user taps the screen I want the camera to focus on that point

This is my code:

 func focusCamera(point:CGPoint)
    {
        var screenRect:CGRect = bounds
        var focusX = Float(point.x/screenRect.width)
        var focusY = Float(point.y/screenRect.height)

        _currentDevice.lockForConfiguration(nil)
        _currentDevice.setFocusModeLockedWithLensPosition(focusX)
        {
            time in
            self._currentDevice.unlockForConfiguration()
        }

        _currentDevice.setFocusModeLockedWithLensPosition(focusY)
        {
                time in
                self._currentDevice.unlockForConfiguration()
        }
    }

But it doesnt seem to work.

Any suggestions are more than welcome!


Solution

  • Turns out its very simple:

    _currentDevice.lockForConfiguration(nil)
    _currentDevice.focusPointOfInterest = tap.locationInView(self)
    _currentDevice.unlockForConfiguration()