Неактивное / недействительное соединение прошло при попытке сделать фотографию
Я пытаюсь сделать фотографию, используя пользовательский вид (без использования UIImagePickerController
), но всякий раз, когда я пытаюсь сделать фотографию, приложение вылетает, и выдается эта ошибка:
Завершение работы приложения из-за необработанного исключения "NSInvalidArgumentException", причина: "-[AVCaptureStillImageOutput captureStillImageAsynchronouslyFromConnection: завершению Handler:] - неактивное / недействительное соединение передано".
Вот мой takePhoto()
функция, которая вызывает ошибку:
func takePhoto(sender: UIButton!){
var still: AVCaptureStillImageOutput = AVCaptureStillImageOutput()
var connection: AVCaptureConnection = AVCaptureConnection(inputPorts: self.input.ports, output: still)
if(connection.enabled){
still.captureStillImageAsynchronouslyFromConnection(connection, completionHandler: {(buffer: CMSampleBuffer!, error: NSError!) -> Void in
println("picture taken")//this never gets executed
})
}
}
Я также попытался установить connection
переменная в takePhoto()
функция для:
self.output.connections[0] as AVCaptureConnection
так же как
(self.session.outputs[0] as AVCaptureOutput).connections[0] as AVCaptureConnection
и я получаю тот же результат.
На том же виде, что и кнопка " Сделать фото", также есть предварительный просмотр камеры (что работает):
func setupCamera(){
self.session = AVCaptureSession()
self.session.sessionPreset = AVCaptureSessionPreset640x480
self.session.beginConfiguration()
self.session.commitConfiguration()
var error: NSError?
var devices: [AVCaptureDevice] = AVCaptureDevice.devices() as [AVCaptureDevice]
for device in devices{
if(device.hasMediaType(AVMediaTypeVideo) && device.supportsAVCaptureSessionPreset(AVCaptureSessionPreset640x480)){
//the input variable is initialized here
self.input = AVCaptureDeviceInput.deviceInputWithDevice(device as AVCaptureDevice, error: &error) as AVCaptureDeviceInput
if(self.session.canAddInput(self.input)){
self.session.addInput(self.input)
break
}
}
}
var settings = [kCVPixelBufferPixelFormatTypeKey:kCVPixelFormatType_32BGRA]
//the output variable is initialized here
self.output = AVCaptureVideoDataOutput()
self.output.videoSettings = settings
self.output.alwaysDiscardsLateVideoFrames = true
if(self.session.canAddOutput(self.output)){
self.session.addOutput(self.output)
}
var captureLayer = AVCaptureVideoPreviewLayer(session: self.session)
captureLayer.frame = CGRectMake(0, 64, self.view.frame.width, (self.view.frame.width * 4) / 3)
self.view.layer.addSublayer(captureLayer)
self.session.startRunning()
}
Я тестирую это на своем iPhone 5s, и все работает, включая предварительный просмотр, кроме takePhoto()
функция.
Есть ли способ сделать это, или я должен использовать UIImagePickerController
?
2 ответа
При настройке камеры добавьте stillImageOutput к вашему AVCaptureSession
,
self.stillImageOutput = AVCaptureStillImageOutput()
let stillSettings = [AVVideoCodecJPEG:AVVideoCodecKey]
self.stillImageOutput.outputSettings = stillSettings
if(self.session.canAddOutput(self.stillImageOutput)){
self.session.addOutput(self.stillImageOutput)
}
Затем при съемке, получить AVCaptureSession
из stillImageOutput.
func takePhoto(sender: UIButton!){
let connection = self.stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
if(connection.enabled){
self.stillImageOutput.captureStillImageAsynchronouslyFromConnection(connection, completionHandler: {(buffer: CMSampleBuffer!, error: NSError!) -> Void in
println("picture taken") // Now, this is executed
})
}
}
Кто бы ни связался с этим вопросом из-за сбоев или чего-то, что вы не можете воспроизвести:
Пользователь запретил доступ к камере. Проверьте, разрешено ли разрешение камеры. Я получил производственные сбои, и это оказалось так.