Toggle CAMERA flash on the push of a button; AVFoundation/Swift

扶醉桌前 提交于 2019-12-24 06:47:09

问题


Im using AVFoundation to create a custom camera. It needs to have a flash button that on press, toggles the flash on and off. I am not asking about torch, there are plenty of answers for torch. Because AVFoundation has been deprecated, most answers online don't work anymore. Also, I need to guard against the possibility the user doesn't have a front flash.

This is the code I have tried with no luck:

    private func flashOn(device:AVCaptureDevice)
{
    do{
        if (device.hasFlash)
        {
            try device.lockForConfiguration()
            let photoSettings = AVCapturePhotoSettings()
            photoSettings.flashMode = .on
            device.flashMode = .on
            device.unlockForConfiguration()
        }
    }catch{
        //DISABEL FLASH BUTTON HERE IF ERROR
        print("Device tourch Flash Error ");
    }
}

private func flashOff(device:AVCaptureDevice)
{
    do{
        if (device.hasFlash){
            try device.lockForConfiguration()
            let photoSettings = AVCapturePhotoSettings()
            photoSettings.flashMode = .off
            device.flashMode = .off
            device.unlockForConfiguration()
        }
    }catch{
        //DISABEL FLASH BUTTON HERE IF ERROR
        print("Device tourch Flash Error ");
    }
}

func toggleFlash() {
    var device : AVCaptureDevice!

    if #available(iOS 10.0, *) {
        let videoDeviceDiscoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera, .builtInDuoCamera], mediaType: AVMediaTypeVideo, position: .unspecified)!
        let devices = videoDeviceDiscoverySession.devices!
        device = devices.first!

    } else {
        // Fallback on earlier versions
        device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    }

    if ((device as AnyObject).hasMediaType(AVMediaTypeVideo))
    {
        if (device.hasFlash)
        {
            self.session.beginConfiguration()
            //self.objOverlayView.disableCenterCameraBtn();
            if device.isFlashActive == false {
                self.flashOn(device: device)
            } else {
                self.flashOff(device: device);
            }
            //self.objOverlayView.enableCenterCameraBtn();
            self.session.commitConfiguration()
        }
    }
}

Then I call it in my VC

    @IBAction func flashBtnPressed(_ sender: Any) {
    toggleFlash()
}

Here is what Ive tried: How to turn the iPhone camera flash on/off swift 2?

来源:https://stackoverflow.com/questions/45599549/toggle-camera-flash-on-the-push-of-a-button-avfoundation-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!