I've implemented the code below to change the orientation of an AVCaptureVideoSession
based upon the UIInterfaceOrientation
:
- (AVCaptureVideoOrientation)interfaceOrientationToVideoOrientation:(UIInterfaceOrientation)orientation {
switch (orientation) {
case UIInterfaceOrientationPortrait:
return AVCaptureVideoOrientationPortrait;
case UIInterfaceOrientationPortraitUpsideDown:
return AVCaptureVideoOrientationPortraitUpsideDown;
case UIInterfaceOrientationLandscapeLeft:
return AVCaptureVideoOrientationLandscapeLeft;
case UIInterfaceOrientationLandscapeRight:
return AVCaptureVideoOrientationLandscapeRight;
default:
break;
}
NSLog(@"Warning - Didn't recognise interface orientation (%ld)",(long)orientation);
return AVCaptureVideoOrientationPortrait;
}
This code works almost perfectly. However, one problem that occurs is that if you quickly rotate the iOS device 180 degrees, the camera will be shown upside down.
Here's what the camera view looks like before the rotation:
And here's what it looks like after the rotation:
Additionally, here is my implementation of viewDidLayoutSubviews
:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
previewLayer.frame = self.view.bounds;
self.view.translatesAutoresizingMaskIntoConstraints = NO;
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:previewLayer];
if (previewLayer.connection.supportsVideoOrientation) {
previewLayer.connection.videoOrientation = [self interfaceOrientationToVideoOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
}
Does anyone have an idea of why the camera view would be upside down when this 180-degree rotation occurs?
I had the same issue before here what solved my issue.
I declared a global variable:
Under
implementation
(.m file) i declared NSNotification observer under-viewWillAppear
like:I made a function that returns the orientation of the copied current device like:
Take a loot at my
-interfaceOrientationToVideoOrientation
method, it converts theiOSDevice.orientation
intoAVCaptureVideoOrientation
same with what you have there..(In my case i needed this functions below, but take a look at it might be useful to you for some reason)
Edit
For default orientation: You need to check the "current" orientation.
Note:
Using
NSNotificationCenter
let the rotation of the device to be settled first before triggered..Hope this have help you..