2017-02-01 77 views
0

我想觀察火炬的狀態並設置一個按鈕的tintColor,但不調用observeValue。我究竟做錯了什麼?如何觀察AVCaptureDevice.isTorchActive

ViewController.swift

import UIKit 
import AVFoundation 

class ViewController: UIViewController { 

    @IBOutlet weak var previewView: PreviewView! 
    private let session = AVCaptureSession() 
    private var videoDevice: AVCaptureDevice! 
    private var observeContext = 0; 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Assume access is granted 
     previewView.session = session 
     sessionQueue.async { [unowned self] in 
      self.configureSession() 
     } 
    } 

    override func viewWillAppear(_ animated: Bool) { 
     super.viewWillAppear(animated) 
     sessionQueue.async { [unowned self] in 
      self.session.startRunning(); 
     } 
    } 

    override func viewWillDisappear(_ animated: Bool) { 
     sessionQueue.async { [unowned self] in 
      if self.session.isRunning { 
       self.session.stopRunning() 
      } 
      if let device = self.videoDevice { 
       device.removeObserver(self, forKeyPath: #keyPath(AVCaptureDevice.isTorchActive)) 
      } 
     } 
     super.viewWillDisappear(animated) 
    } 

    private func configureSession() { 
     session.beginConfiguration() 
     do { 
      if let backCameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .back) { 
       self.videoDevice = backCameraDevice 

       backCameraDevice.addObserver(self, forKeyPath: #keyPath(AVCaptureDevice.isTorchActive), options: [.new], context: &observeContext) 

       let videoDeviceInput = try AVCaptureDeviceInput(device: backCameraDevice) 
       if session.canAddInput(videoDeviceInput) { 
        session.addInput(videoDeviceInput) 
       } 
      } 
     } 
     catch { 
      print("Could not create video device input: \(error)") 
     } 
     session.commitConfiguration() 
    } 

    @IBAction func btnClick(_ sender: Any) { 
     sessionQueue.async { [unowned self] in 
      if let device = self.videoDevice, device.isTorchAvailable { 
       do { 
        try device.lockForConfiguration() 
        if device.isTorchActive { 
         device.torchMode = .off 
        } else { 
         device.torchMode = .on 
        } 
        device.unlockForConfiguration() 
       } catch { 
        print("Could not configure torch: \(error)") 
       } 
      } 
     } 
    } 

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { 
     let newValue = change?[.newKey] 

     if context == &observeContext { 
      print(newValue) 
     } else { 
      super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) 
     } 
    } 
} 

回答

0

使用#keyPath(AVCaptureDevice.torchActive) - 注意缺乏is。您必須通過Objective-C名稱來觀察屬性,而不是通過「renamification」Swift 3名稱。