UIImagePickerController InterfaceOrientation Crash

2019-06-26 09:06发布

问题:

Ever since updating my device to 6.1, I'm getting a crash when trying to show the UIImagePickerController. I only use Portrait orientation.

The Crash:

Reason: * Terminating app due to uncaught exception 'UIApplicationInvalidInterfaceOrientation', reason: 'preferredInterfaceOrientationForPresentation must return a supported interface orientation!'

Here is where I call the UIImagePickerController:

if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
    //The device cannot make pictures
    [PMAlertDialog showWithTitle:NSLocalizedString(@"incompatibleDeviceDialogTitle", nil) message:NSLocalizedString(@"incompatibleDeviceDialogMessage", nil) andButtonTitle:NSLocalizedString(@"okButtonTitle", nil)];
    return;
}

if (_imagePicker == nil)
{
    _imagePicker = [[UIImagePickerController alloc] init];
    _imagePicker.delegate = self;
}

_imagePicker.allowsEditing = NO;
_imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
_imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];

[self presentModalViewController:_imagePicker animated:YES];

I've added these methods to the view controller where the UIImagePickerController is added:

-(BOOL)shouldAutorotate
{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

回答1:

To fix the issue, I made a category as follows:

I created a new objective-c class, "UIImagePickerController+NonRotating"

In the header file (UIImagePickerController+NonRotating.h):

#import <Foundation/Foundation.h>

@interface UIImagePickerController (NonRotating)

- (BOOL)shouldAutorotate;
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation;

@end

In the implementation file (UIImagePickerController+NonRotating.m):

#import "UIImagePickerController+NonRotating.h"

@implementation UIImagePickerController (NonRotating)

- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

@end

You could of course modify this however you see fit -- making it autorotate and returning multiple supported orientations, etc.