How to turn flashlight ON and OFF in swift?

前端 未结 11 1495
青春惊慌失措
青春惊慌失措 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:12

    Updated Swift 4 Answer:

    func toggleTorch(on: Bool) {
        guard 
            let device = AVCaptureDevice.default(for: AVMediaType.video),
            device.hasTorch
        else { return }
    
        do {
            try device.lockForConfiguration()
            device.torchMode = on ? .on : .off                    
            device.unlockForConfiguration()
        } catch {
            print("Torch could not be used")
        }
    }
    

    Then to actually turn it on or off, call the function and pass in a true or false boolean.

    toggleTorch(on: true) of toggleTorch(on: false)

    I got this answer from Hacking with Swift, however their example had an error in it.

    They used AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) but this produces an error saying defaultDevice doesn't exist. So I changed it to AVCaptureDevice.default(for: AVMediaType.video)

提交回复
热议问题