diff --git a/SelfieRingLight/Features/Camera/CameraPreview.swift b/SelfieRingLight/Features/Camera/CameraPreview.swift index 07e7d08..e761409 100644 --- a/SelfieRingLight/Features/Camera/CameraPreview.swift +++ b/SelfieRingLight/Features/Camera/CameraPreview.swift @@ -153,6 +153,9 @@ class CameraPreviewUIView: UIView { updatePreviewOrientation() } + /// Tracks the last valid orientation for fallback + private var lastValidOrientation: UIDeviceOrientation = .portrait + @objc private func handleOrientationChange() { updatePreviewOrientation() } @@ -161,9 +164,36 @@ class CameraPreviewUIView: UIView { guard let connection = previewLayer?.connection else { return } // Get rotation angle based on device orientation - let deviceOrientation = UIDevice.current.orientation + var deviceOrientation = UIDevice.current.orientation + + // If device orientation is flat or unknown, try to get from interface orientation + if !deviceOrientation.isValidInterfaceOrientation { + // Use last known good orientation, or get from window scene + if let windowScene = window?.windowScene { + switch windowScene.interfaceOrientation { + case .portrait: + deviceOrientation = .portrait + case .portraitUpsideDown: + deviceOrientation = .portraitUpsideDown + case .landscapeLeft: + deviceOrientation = .landscapeRight // Interface and device are inverted + case .landscapeRight: + deviceOrientation = .landscapeLeft // Interface and device are inverted + case .unknown: + deviceOrientation = lastValidOrientation + @unknown default: + deviceOrientation = lastValidOrientation + } + } else { + deviceOrientation = lastValidOrientation + } + } else { + // Store this as the last valid orientation + lastValidOrientation = deviceOrientation + } // Calculate rotation angle (in degrees) for the preview layer + // For front camera in portrait: sensor is landscape, so rotate 90° let rotationAngle: CGFloat switch deviceOrientation { case .portrait: @@ -174,10 +204,7 @@ class CameraPreviewUIView: UIView { rotationAngle = 180 case .landscapeRight: rotationAngle = 0 - case .faceUp, .faceDown, .unknown: - // Keep current orientation for flat/unknown positions - return - @unknown default: + default: rotationAngle = 90 // Default to portrait }