How to turn flashlight ON and OFF in swift?

前端 未结 11 1489
青春惊慌失措
青春惊慌失措 2020-12-02 15:42

I\'d like to add flashlight functionality to my app in Swift. How can I go about doing that?

11条回答
  •  长情又很酷
    2020-12-02 16:09

    For xcode 9.1, swift 4 (updated to not crash if no torch):

       func toggleFlash() {
        let device = AVCaptureDevice.default(for: AVMediaType.video)
    
        if (device != nil) {
            if (device!.hasTorch) {
                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)
                }
            }
        }
    }
    

提交回复
热议问题