我正在尝试显示相机视图,正如您在下面的代码中所看到的,我将其设置为显示任何错误并且如果发生任何错误则不会中断程序,但是当我运行此代码时不会发生错误或显示摄像机视图。我在实际的手机上运行它,手机确实要求它是否有权使用相机。以下是代码
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var input : AVCaptureDeviceInput?
let error : NSError?
do {
input = try AVCaptureDeviceInput(device: backCamera)
} catch let error as NSError? {
print(error)
if error == nil && (captureSession?.canAddInput(input))!{
captureSession?.addInput(input)
videoOutput = AVCaptureVideoDataOutput()
//videoOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecKey]
if ((captureSession?.canAddOutput(videoOutput)) != nil){
captureSession?.addOutput(videoOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
}
}
}
答案 0 :(得分:1)
只有在发生错误时才执行catch的主体。因此,由于您的代码位于catch块内,因此它不会执行,因为它没有发现任何错误。 因此,请从catch块中删除代码,并按照@penatheboss的建议将其放在外面。
答案 1 :(得分:0)
不要将代码放在catch
中。那就是出现问题。
do {
input = try AVCaptureDeviceInput(device: backCamera)
} catch let error as NSError? {
print(error)
return//Stop rest of code
}
if (captureSession?.canAddInput(input))!{
captureSession?.addInput(input)
videoOutput = AVCaptureVideoDataOutput()
//videoOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecKey]
if ((captureSession?.canAddOutput(videoOutput)) != nil){
captureSession?.addOutput(videoOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
}