Search code examples
swiftxcodeavcapturesession

Allow AVCaptureVideoPreviewLayer preview rotate with device


I have a AVCaptureVideoPreviewLayer in my app, and it works fine on devices in portrait, but in landscape, the video is sideways. I tried

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .all
}

But the issue persists.


Solution

  • I fixed it - I just had to add this-

        if UIDevice.current.orientation == .portrait {
            previewLayer.connection?.videoOrientation = .portrait
        } else if UIDevice.current.orientation == .portraitUpsideDown {
            previewLayer.connection?.videoOrientation = .portraitUpsideDown
        } else if UIDevice.current.orientation == .landscapeLeft {
            previewLayer.connection?.videoOrientation = .landscapeRight
        } else if UIDevice.current.orientation == .landscapeRight {
            previewLayer.connection?.videoOrientation = .landscapeLeft
        }
    

    -which gets called when the device is rotated. I also call it on startup after I have initialized the AVCaptureVideoPreviewLayer.