Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get devices using AVCaptureDevice

I've managed to find some code that would give me access to the devices of a phone (such as the camera). The issue is that when I compile the code (and I'm printing the different devices) using Xcode, I get an empty array.

Here is what I wrote:

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

    }

  }

Do you have any ideas as to why I am getting an empty array?

like image 602
Tricks Avatar asked Jun 29 '15 15:06

Tricks


2 Answers

If you're only running it in the simulator, the array will always be empty because it has no physical hardware to choose from. In fact, if you try to access physical hardware inside the Simulator, it will crash. If you plug a device in and still get an empty array, let me know.

like image 78
pbush25 Avatar answered Oct 22 '22 14:10

pbush25


first check the current status of the authorization

AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)

more detail you can read this article

like image 36
nathanwhy Avatar answered Oct 22 '22 12:10

nathanwhy