PolandSpring PolandSpring - 5 days ago 6
Swift Question

Enum conversion of UIInterfaceOrientation to AVCaptureVideoOrientation in Swift

I'm playing around with using AVFoundation in Swift

Normally when I set up a video camera capture session I do something like the following in objective-c

[[cameraView.previewLayer connection] setVideoOrientation:(AVCaptureVideoOrientation)[self interfaceOrientation]]


In swift it seems like I have to do something like this (because of optional type)

if let connection = cameraView.previewLayer?.connection {
connection.videoOrientation = self.interfaceOrientation as AVCaptureVideoOrientation
}


however this complains with

‘AVCaptureVideoOrientation’ is not a subtype of ‘UIInterfaceOrientation’


After reading about the down-casting methodology this makes a lot of sense, but I'm struggling to find how to actually get this working.

Do I need to write a helper method that basically does a switch statement through all the available values of UIInterfaceOrientation to get this working?

Answer

As I noted in my comments, since AVCaptureVideoOrientation and UIInterfaceOrientation don't match up their cases, you can use something like:

extension AVCaptureVideoOrientation {
    var uiInterfaceOrientation: UIInterfaceOrientation {
        get {
            switch self {
            case .LandscapeLeft:        return .LandscapeLeft
            case .LandscapeRight:       return .LandscapeRight
            case .Portrait:             return .Portrait
            case .PortraitUpsideDown:   return .PortraitUpsideDown
            }
        }
    }

    init(ui:UIInterfaceOrientation) {
        switch ui {
        case .LandscapeRight:       self = .LandscapeRight
        case .LandscapeLeft:        self = .LandscapeLeft
        case .Portrait:             self = .Portrait
        case .PortraitUpsideDown:   self = .PortraitUpsideDown
        default:                    self = .Portrait
        }
    }
}

then use it as:

if let connection = cameraView.previewLayer?.connection {
    connection.videoOrientation = AVCaptureVideoOrientation(ui:self.interfaceOrientation)
}
Comments