在Swift中无法使用前置摄像头

时间:2017-03-01 03:07:46

标签: ios swift camera

我想制作前置摄像头,但是在Swift中无法构建前置摄像头,即使我可以构建相机。

当我只改变"返回"到#34;前面",相机没有工作......

如何使用前置摄像头?

var captureSesssion: AVCaptureSession!
var stillImageOutput: AVCapturePhotoOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
var captureDevice : AVCaptureDevice!

override func viewDidLoad() {
    super.viewDidLoad()

    captureSesssion = AVCaptureSession()
    stillImageOutput = AVCapturePhotoOutput()

    captureSesssion.sessionPreset = AVCaptureSessionPreset1920x1080 

    captureDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front) 
    //When change "front" to "back", camera is built.

    do {
       let input = try AVCaptureDeviceInput(device: captureDevice)

       if (captureSesssion.canAddInput(input)) {
           captureSesssion.addInput(input)

           if (captureSesssion.canAddOutput(stillImageOutput)) {
               captureSesssion.addOutput(stillImageOutput)
               captureSesssion.startRunning() 

               previewLayer = AVCaptureVideoPreviewLayer(session: captureSesssion)
               previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect 
               previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait 

               self.view.layer.addSublayer(previewLayer!)

               previewLayer?.position = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
               previewLayer?.bounds = self.view.frame
           }
       }
    }
    catch {
        print(error)
    }

1 个答案:

答案 0 :(得分:4)

适用于iPhone 7和iPhone 7 Plus的前置摄像头可以录制1080p,但在较旧型号上它只能录制720p。因此,您只需要更改会话预设,即:

select col1,col2,
greatest(
    nvl(col1,to_date('1901-01-01','YYYY-MM-DD')),
    nvl(col2,to_date('1901-01-01','YYYY-MM-DD'))
        ) as col3
from your_table;

Swift 4:

captureSesssion.sessionPreset = AVCaptureSessionPreset1280x720