Captured photos in wrong orientation

I'm building a custom camera screen that displays the camera image on a preview layer and then captures an image, using AVCaptureSession. When the picture is captured, I immediately load it into a UIImageView in order to display it to the user for approval.

I've actually done this many times before, but this is the first time I've tried to do it in an app that supports interface rotation. If I hold the phone in Portrait mode and capture a picture, everything works as expected.

When the user rotates the phone into Landscape orientation, I detect this and I replace the preview layer (AVCaptureVideoPreviewLayer) with a new one, specifying connection.videoRotationAngle in order to make the image appear in the right orientation. I'm a little surprised that this is necessary, and it's not a smooth transition, but that doesn't matter.

What does matter is that when I capture the image, it is in the wrong orientation. I tried rotating it myself, but this doesn't seem to make any difference. What am I doing wrong?

I don't think you should need to create a new layer – you should be able to just set previewLayer.connection.videoRotationAngle directly as its a writable property.

AVFoundation also states that the buffers themselves may not be rotated (e.g. that the top-left pixel may not be logically at the 0th pixel index in the buffer). UIImage handles images like this by taking an imageOrientation during creation - you may need to in turn set that when you are creating the UIImage from the capture.

Captured photos in wrong orientation
 
 
Q