我设法找到了一些代码,可以让我访问手机的设备(例如相机)。问题是,当我使用 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/