问题
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