Can't get devices using AVCaptureDevice

I was able to find a code that would give me access to phone devices (for example, a camera). The problem is when I compile the code (and I print to different devices) with Xcode, I get an empty array.

Here's 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?

+3


source to share


3 answers


If you only run it in a simulator, the array will always be empty because it has no physical hardware. In fact, if you try to access the physical hardware inside the simulator, it will work. If you plug in a device and still get an empty array, please let me know.



+6


source


first check the current authorization status

AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)

      



you can read in more detail in this article

+4


source


Check current authorization status for Swift 4

 AVCaptureDevice.authorizationStatus(for: AVMediaType.video)

      

0


source







All Articles