只需按一下按钮,即可切换CAMERA闪光灯; AVFoundation /斯威夫特

时间:2017-08-09 19:54:00

标签: ios swift avfoundation

我正在使用AVFoundation来创建自定义相机。它需要有一个按下的闪光按钮,可以打开和关闭闪光灯。我不是在问火炬,火炬有很多答案。由于AVFoundation已被弃用,因此大多数在线答案都不再适用。另外,我需要防止用户没有前置闪光灯的可能性。

这是我试过的代码没有运气:

    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()
        }
    }
}

然后我在我的VC中调用它

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

以下是我尝试的内容: How to turn the iPhone camera flash on/off swift 2?

0 个答案:

没有答案