Monday, April 20, 2015

AVCaptureTorchMode - Flashlight / Torch function

1. Drag a button to the storyboard. Make the text as "OFF".

2. Control-drag the button to ViewController.swift and make it an IBAction:

    @IBAction func myButton(sender: AnyObject) {
    }

3. Complete the code as below:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBAction func myButton(sender: AnyObject) {
        
        let myDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        
        if (myDevice.hasTorch) {
            myDevice.lockForConfiguration(nil)
            if (sender.titleLabel!?.text == "ON")
            {
                myDevice.torchMode = AVCaptureTorchMode.Off
                sender.setTitle("OFF", forState:  UIControlState.Normal);
            }
            else
            {
                myDevice.torchMode = AVCaptureTorchMode.On
                sender.setTitle("ON", forState:  UIControlState.Normal);
            }
            myDevice.unlockForConfiguration()
        } else {
            let alertView = UIAlertView()
            alertView.message = "No Flash Detected!"
            alertView.addButtonWithTitle("OK")
            alertView.show()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

    }

========================

No comments:

Post a Comment