I\'ve been tearing my hair out trying to get the AVFoundation camera to capture a picture in the correct orientation (i.e. the device orientation) but I can\'t get it to wor
Update the orientation in the preview layer after start the capture session and whenever the device is rotated.
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { [weak self] context in
if let connection = self?.previewLayer?.connection, connection.isVideoOrientationSupported {
if let orientation = AVCaptureVideoOrientation(orientation: UIDevice.current.orientation) {
connection.videoOrientation = orientation
}
}
}, completion: nil)
super.viewWillTransition(to: size, with: coordinator)
}
extension AVCaptureVideoOrientation {
init?(orientation: UIDeviceOrientation) {
switch orientation {
case .landscapeRight: self = .landscapeLeft
case .landscapeLeft: self = .landscapeRight
case .portrait: self = .portrait
case .portraitUpsideDown: self = .portraitUpsideDown
default: return nil
}
}
}