无法使用AVCaptureDevice

时间:2015-06-29 15:22:56

标签: ios swift camera avcapturesession avcapturedevice

我设法找到了一些可以让我访问手机设备(例如相机)的代码。问题是,当我使用Xcode编译代码(并且我正在打印不同的设备)时,我得到一个空数组。

这是我写的:

import UIKit
import AVFoundation

class ViewController: UIViewController {

  let captureSession = AVCaptureSession()
  var previewLayer : AVCaptureVideoPreviewLayer?

  // If we find a device we'll store it here for later us
  var captureDevice : AVCaptureDevice?

  override func viewDidLoad() {
    super.viewDidLoad()            
    // Do any additional setup after loading the view, typically from a nib.

    captureSession.sessionPreset = AVCaptureSessionPresetHigh

    let devices = AVCaptureDevice.devices()
    println(devices)
    // Loop through all the capture devices on this phone
    for (device in devices) {
        // Make sure this particular device supports video
        if (device.hasMediaType(AVMediaTypeVideo)) {
         // Finally check the position and confirm we've got the back camera
            if(device.position == AVCaptureDevicePosition.Back) {
                captureDevice = device as? AVCaptureDevice
                if captureDevice != nil {
                    println("Capture device found")
                    beginSession()
                }
            }
        }
      }

    }

    func beginSession() {

      var err : NSError? = nil
      captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))

      if err != nil {
          println("error: \(err?.localizedDescription)")
      }

      previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
      self.view.layer.addSublayer(previewLayer)
      previewLayer?.frame = self.view.layer.frame

      captureSession.startRunning()

    }

  }

你对我为什么得到一个空阵列有任何想法吗?

3 个答案:

答案 0 :(得分:6)

如果您只在模拟器中运行它,则阵列将始终为空,因为它没有可供选择的物理硬件。实际上,如果您尝试访问模拟器中的物理硬件,它将崩溃。如果你插入一个设备并仍然得到一个空数组,请告诉我。

答案 1 :(得分:4)

首先检查授权的当前状态

AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)

您可以阅读更多细节this article

答案 2 :(得分:0)

检查Swift 4的当前授权状态

 AVCaptureDevice.authorizationStatus(for: AVMediaType.video)