Preview doesn't show up (AVCaptureVideoPreviewLayer)

时间:2018-09-22 22:37:41

标签: ios swift video avfoundation video-capture

I'm trying to first just get my app to show the camera preview of the wide angle camera. But what I do it just doesn't show up. (the app has video and audio permission and is being tested on an iPhone 7 Plus)

Here's my session configuration code:

func configureSession() throws {
    session.beginConfiguration()

    // configure inputs
    let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
    let audioDevice = AVCaptureDevice.default(.builtInMicrophone, for: .audio, position: .unspecified)
    guard let videoInput = try? AVCaptureDeviceInput(device: videoDevice!), let audioInput = try? AVCaptureDeviceInput(device: audioDevice!), session.canAddInput(videoInput), session.canAddInput(audioInput) else {
        throw CameraError.configurationFailed
    }

    // configure outputs
    let output = AVCaptureMovieFileOutput()
    let previewOutput = AVCaptureVideoDataOutput()
    previewOutput.alwaysDiscardsLateVideoFrames = true
    previewOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String : NSNumber(value: kCVPixelFormatType_32BGRA)]
    guard session.canAddOutput(output) && session.canAddOutput(previewOutput) else {
        throw CameraError.configurationFailed
    }
    session.sessionPreset = .high
    session.addOutput(output)
    session.addOutput(previewOutput)

    session.commitConfiguration()
}

and this is the code for the previewLayer:

// adds given view as previewView to the session
func configureAsPreview(_ view: UIView) {
    let previewLayer = AVCaptureVideoPreviewLayer(session: session)
    view.layer.addSublayer(previewLayer)
    previewLayer.frame = view.layer.frame
}

and it is being called in viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    if cameraManager.hasPermissionForVideo {
        try! cameraManager.configureSession()
        cameraManager.configureAsPreview(self.previewView)
        cameraManager.startSession()
    } else {
        performSegue(withIdentifier: "presentPermissions", sender: nil)
    }
}

What am I doing wrong? I really can't figure it out and it's probably just something stupidly small.

Thanks.

1 个答案:

答案 0 :(得分:0)

尝试在需要时更新图层框架,并使用bounds代替frame。图层不支持自动调整大小,您需要手动进行管理。

private var __previewLayer = AVCaptureVideoPreviewLayer? = nil
func configureAsPreview(_ view: UIView) {
    let previewLayer = AVCaptureVideoPreviewLayer(session: session)
    self.view.layer.addSublayer(previewLayer)
    previewLayer.frame = self.view.bounds
    self.__previewLayer = previewLayer
}

override viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.__previewLayer?.frame = self.view.bounds
}