我正在尝试用AVFoundation制作一张照片。当我将obj-c代码转换为swift来执行此操作时,我的程序在运行部件时遇到问题,我试图找到一个videoConnection。任何线索为什么?
let captureSesion = AVCaptureSession()
var captureDevice : AVCaptureDevice?
let stillImageOutput = AVCaptureStillImageOutput()
captureSesion.sessionPreset = AVCaptureSessionPresetPhoto
let devices = AVCaptureDevice.devices()
println(devices)
for device in devices{
if device.hasMediaType(AVMediaTypeVideo){
if device.position == AVCaptureDevicePosition.Back{
captureDevice = device as? AVCaptureDevice
}
}
}
if captureDevice != nil{
var err : NSError? = nil
captureSesion.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
//preview
var previewLayer = AVCaptureVideoPreviewLayer(session: captureSesion)
self.view.layer.addSublayer(previewLayer)
previewLayer?.frame = self.view.layer.frame
var outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
stillImageOutput.outputSettings = outputSettings
captureSesion.addOutput(stillImageOutput)
captureSesion.startRunning()
//take photo
var videoConnection : AVCaptureConnection?
//only have one conniption and debug get stuck here!!
for connection in self.stillImageOutput.connections{
for port in connection.inputPorts!{
if port.mediaType == AVMediaTypeVideo{
videoConnection = connection as? AVCaptureConnection
break //for ports
}
}
if videoConnection != nil{
break //for connections
}
}
//Take a photo and show
}
}
我成功获取设备和实时预览,但我无法获取stillImageOutput的videoConnection。
[<AVCaptureFigVideoDevice: 0x14d4c660 [Back Camera][com.apple.avfoundation.avcapturedevice.built-in_video:0]>, <AVCaptureFigVideoDevice: 0x14e904d0 [Front Camera][com.apple.avfoundation.avcapturedevice.built-in_video:1]>, <AVCaptureFigAudioDevice: 0x14e8a6d0 [iPod Microphone][com.apple.avfoundation.avcapturedevice.built-in_audio:0]>]
stilImageOutput已添加 寻找联系 1 (LLDB)
答案 0 :(得分:2)
好的,我解决了我的问题。帮助别人的锄头。所以这里的问题是:
var videoConnection : AVCaptureConnection?
//only have one conniption and debug get stuck here!!
for connection in self.stillImageOutput.connections{
for port in connection.inputPorts!{
if port.mediaType == AVMediaTypeVideo{
videoConnection = connection as? AVCaptureConnection
break //for ports
}
}
if videoConnection != nil{
break //for connections
}
}//take a photo then
该代码是我将其objective-c版本翻译为swift的方式。我在网上发现了类似的尝试。然而,在迅捷中,一切都变得如此简单(但并不明显)。所以这一行解决了这个问题:
if let videoConnection = stillImageOuput.connectionWithMediaType(AVMediaTypeVideo){//take a photo here}