我想在我的Swift应用程序中添加手电筒功能。我该怎么做呢?
更新#1: (torchActive没有返回预期值,这或许是因为它已经修改)
torchActive
更新#2: 对于Swift 2.0
要将闪光灯从打开切换到关闭(不仅像疯猪的回答中那样“打开”),还可以使用以下方法:
func toggleFlash() { let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) if (device.hasTorch) { do { try device.lockForConfiguration() if (device.torchMode == AVCaptureTorchMode.On) { device.torchMode = AVCaptureTorchMode.Off } else { do { try device.setTorchModeOnWithLevel(1.0) } catch { print(error) } } device.unlockForConfiguration() } catch { print(error) } } }
我使用嵌套的do-catch块来实现注释中的Awesomeness建议。这样,即使try device.setTorchModeOnWithLevel(1.0)发生故障,也可以将设备正确解锁以进行配置。
try device.setTorchModeOnWithLevel(1.0)
更新#3: 对于Swift 4:
(我根据个人喜好对代码进行了编辑)
func toggleFlash() { guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return } guard device.hasTorch else { return } do { try device.lockForConfiguration() if (device.torchMode == AVCaptureDevice.TorchMode.on) { device.torchMode = AVCaptureDevice.TorchMode.off } else { do { try device.setTorchModeOn(level: 1.0) } catch { print(error) } } device.unlockForConfiguration() } catch { print(error) } }
原始答案:
func toggleFlash() { let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) if (device.hasTorch) { device.lockForConfiguration(nil) let torchOn = !device.torchActive device.setTorchModeOnWithLevel(1.0, error: nil) device.torchMode = torchOn ? AVCaptureTorchMode.On : AVCaptureTorchMode.Off device.unlockForConfiguration() } }