Tri*_*cks 5 camera ios avcapturesession avcapturedevice swift
我设法找到一些代码,可以让我访问手机设备(如相机).问题是,当我使用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()
}
}
Run Code Online (Sandbox Code Playgroud)
你对我为什么得到一个空阵列有任何想法吗?
如果您只在模拟器中运行它,则阵列将始终为空,因为它没有可供选择的物理硬件.实际上,如果您尝试访问模拟器中的物理硬件,它将崩溃.如果你插入一个设备并仍然得到一个空数组,请告诉我.
| 归档时间: |
|
| 查看次数: |
5330 次 |
| 最近记录: |