How do you set previewLayer.connection.videoOrientation in Swift 2?

2k Views Asked by At

In Objective-C you can do this:

if ( UIDeviceOrientationIsPortrait( deviceOrientation ) || UIDeviceOrientationIsLandscape( deviceOrientation ) ) {
    AVCaptureVideoPreviewLayer *previewLayer = (AVCaptureVideoPreviewLayer *)self.previewView.layer;
    previewLayer.connection.videoOrientation = (AVCaptureVideoOrientation)deviceOrientation;
}

But in Swift, what's the best way to translate this last line? You can't do "deviceOrientation as AVCaptureVideoOrientation".

Best I could come up with so far is:

    if(UIDeviceOrientationIsPortrait(deviceOrientation) || UIDeviceOrientationIsLandscape(deviceOrientation)) {
        let myPreviewLayer: AVCaptureVideoPreviewLayer = self.previewLayer
        myPreviewLayer.connection.videoOrientation = AVCaptureVideoOrientation.init(rawValue: deviceOrientation.rawValue-1)!
    }

But this seems inelegant. The -1 is there because it's just an enum at the end of the day, and the UIDeviceOrientation enum has an "Unknown" one at position 0 that the AVCaptureVideoOrientation does not have...

4

There are 4 best solutions below

0
On

This is the conversion I got:

if UIDeviceOrientationIsPortrait(deviceOrientation) || UIDeviceOrientationIsLandscape(deviceOrientation) {
    var previewLayer: AVCaptureVideoPreviewLayer = previewView.layer
    previewLayer.connection.videoOrientation = deviceOrientation
}

The converter I used tends to not know what the code is supposed to look like some times (Int vs. CGFloat) so it might not work without de-bugging. let me know if it does what you want, for example, the variable could probably be changed to a constant.

0
On

This does a great job on swift 4:

previewLayer.connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: UIApplication.shared.statusBarOrientation.rawValue)!
0
On
connection.videoOrientation = AVCaptureVideoOrientation.Portrait

You can find the constants AVCaptureVideoOrientation values in swift header files. (Swift 2)

0
On

try this

let avLayer = (self.previewView.layer as AVCaptureVideoPreviewLayer)
let connection = avLayer.connection
let orientation = AVCaptureVideoOrientation(rawValue: self.interfaceOrientation.rawValue)!
connection.videoOrientation = orientation