Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn the iPhone camera flash on/off swift 2?

I was looking how to turn on/off the iPhone's camera flash and I found this:

@IBAction func didTouchFlashButton(sender: AnyObject) {
    let avDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

// check if the device has torch
if avDevice.hasTorch {
    // lock your device for configuration
    avDevice.lockForConfiguration(nil)
    // check if your torchMode is on or off. If on turns it off otherwise turns it on
    if avDevice.torchActive {
        avDevice.torchMode = AVCaptureTorchMode.Off
    } else {
        // sets the torch intensity to 100%
        avDevice.setTorchModeOnWithLevel(1.0, error: nil)
    }
    // unlock your device
    avDevice.unlockForConfiguration()
    }
}

I do get 2 issues, one on the line:

avDevice.lockForConfiguration(nil)

and the other on the line:

avDevice.setTorchModeOnWithLevel(1.0, error:nil)

both of them are related to exception handling but I don't know how to resolve them.

like image 509
Roberto Rodriguez Avatar asked Nov 07 '15 17:11

Roberto Rodriguez


2 Answers

@IBAction func didTouchFlashButton(sender: UIButton) {
    let avDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    // check if the device has torch
    if avDevice.hasTorch {
        // lock your device for configuration
        do {
            let abv = try avDevice.lockForConfiguration()
        } catch {
            print("aaaa")
        }

        // check if your torchMode is on or off. If on turns it off otherwise turns it on
        if avDevice.torchActive {
            avDevice.torchMode = AVCaptureTorchMode.Off
        } else {
            // sets the torch intensity to 100%
            do {
                let abv = try avDevice.setTorchModeOnWithLevel(1.0)
            } catch {
                print("bbb")
            }
        //    avDevice.setTorchModeOnWithLevel(1.0, error: nil)
        }
        // unlock your device
        avDevice.unlockForConfiguration()
    }
}
like image 134
Ivan Slavov Avatar answered Oct 13 '22 08:10

Ivan Slavov


Swift 4 version, adapted from Ivan Slavov's answer. "TorchMode.auto" is also an option if you want to get fancy.

    @IBAction func didTouchFlashButton(_ sender: Any) {
    if let avDevice = AVCaptureDevice.default(for: AVMediaType.video) {
        if (avDevice.hasTorch) {
            do {
                try avDevice.lockForConfiguration()
            } catch {
                print("aaaa")
            }

            if avDevice.isTorchActive {
                avDevice.torchMode = AVCaptureDevice.TorchMode.off
            } else {
                avDevice.torchMode = AVCaptureDevice.TorchMode.on
            }
        }
        // unlock your device
        avDevice.unlockForConfiguration()
    }
}
like image 26
nameless Avatar answered Oct 13 '22 08:10

nameless