我嘗試使用自定義視圖拍攝照片(不使用UIImagePickerController
),但每當我嘗試拍攝照片時,應用程序都會崩潰並引發此錯誤:嘗試拍攝照片時通過的無效/無效連接
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AVCaptureStillImageOutput captureStillImageAsynchronouslyFromConnection:completionHandler:] - inactive/invalid connection passed.'
這是我的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
})
}
}
我也試過在takePhoto()
功能設置connection
變量:
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
?