2015-06-29 82 views
2

我已經設法找到一些代碼,可以讓我訪問手機(如相機)的設備。問題是,當我使用Xcode編譯代碼(並打印不同的設備)時,我得到一個空數組。無法使用AVCaptureDevice獲取設備

這裏是我寫的:

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

    } 

    } 

你有任何想法,爲什麼我收到一個空數組?

+0

你們是不是它的設備上? –

回答

5

如果您只在模擬器中運行它,則該陣列將始終爲空,因爲它沒有物理硬件可供選擇。事實上,如果您嘗試訪問模擬器中的物理硬件,它將會崩潰。如果你插入一個設備,仍然有空陣列,讓我知道。

+0

你假設它。 –

+1

是的,我是因爲發佈的代碼與Apple的文檔中的代碼非常相似,並且找不到絕對_zero_'AVCaptureDevices'的常見原因是因爲它正在模擬器中運行。這裏是與OP的代碼文檔:https://developer.apple.com/library/prerelease/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html – pbush25

+1

這絕對是正確的答案..誰在世界downvoted這?? – rigdonmr

3

首先檢查授權

AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) 

更詳細的當前狀態,你可以閱讀this article