ios - 无法使用 AVCaptureDevice 获取设备

标签 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()

    }

  }

关于为什么我得到一个空数组,你有什么想法吗?

最佳答案

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

关于ios - 无法使用 AVCaptureDevice 获取设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31119524/

相关文章:

ios - UIButton 没有出现在表格 View 中?

ios - CTCarrier 在所有属性上返回 nil

ios - "Creating an image format with an unknown type is an error"与 UIImagePickerController

android - SurfaceView 正在交换红色和蓝色的 Google Glass 相机颜色

来自相机或图库的 Android EXIF 数据图像丢失

ios - 为什么滚动 UITableView 比滚动 UIScrollView 响应更快?

ios - 商店套件交易错误 : "Cannot connect to iTunes Store" on ios 7 device

ios - 在 iwatch 中触摸 UITextField 外部时关闭键盘

ios - 在 Swift 中使用单例和解析 JSON

ios - 是否可以在 AVCaptureVideoDataOutput 中设置 AVCaptureSessionPresetPhoto?