Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force View Controller Orientation in iOS 9

I am working on a photography app that allow photos to be taken in portrait or landscape. Due to the requirements of the project, I cannot let the device orientation autorotate, but rotation does need to be supported.

When using the following orientation methods:

override func shouldAutorotate() -> Bool {
    return true
}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if self.orientation == .Landscape {
        return UIInterfaceOrientationMask.LandscapeRight
    } else {
        return UIInterfaceOrientationMask.Portrait
    }
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    if self.orientation == .Landscape {
        return UIInterfaceOrientation.LandscapeRight
    } else {
        return UIInterfaceOrientation.Portrait
    }
}

I am able to set rotation correctly at launch. By changing the orientation value and calling UIViewController.attemptRotationToDeviceOrientation() I am able to support rotation to the new desired interface. However, this rotation only occurs when the user actually moves their device. I need it to happen automatically.

I am able to call: UIDevice.currentDevice().setValue(targetOrientation.rawValue, forKey: "orientation") to force the change, but that causes other side effects because UIDevice.currentDevice().orientation only returns the setValue from that point on. (and it's extremely dirty)

Is there something I'm missing? I've looked into closing and launching a new view controller, but that has other issues such as a constant UI glitch when dismissing and immediately presenting a new view controller.

EDIT:

The following methods did not work for me:

  • Trick preferredInterfaceOrientationForPresentation to fire on viewController change
  • Forcing UIInterfaceOrientation changes on iPhone

EDIT 2:

Thoughts on potential solutions:

  1. set orientation directly (with setValue) and deal with all the side effects this presents on iOS 9 (not acceptable)

  2. I can use the current solution and indicate that the user needs to rotate the device. Once the device has been physically rotated, the UI rotates and then locks in place correctly. (poor UI)

  3. I can find a solution that forces the refresh of orientation and rotates without physical action. (what I'm asking about, and looking for)

  4. Do it all by hand. I can lock the interface in portrait or landscape, and manually rotate and resize the container view. This is 'dirty' because it forgoes all of the size class autolayout features and causes much heavier code. I am trying to avoid this.

like image 246
Nathan Tornquist Avatar asked Jun 17 '16 16:06

Nathan Tornquist


2 Answers

I was able to find a solution with the assistance of this answer: Programmatic interface orientation change not working for iOS

My base orientation logic is as follows:

// Local variable to tracking allowed orientation. I have specific landscape and
// portrait targets and did not want to remember which I was supporting
enum MyOrientations {
    case Landscape
    case Portrait
}
var orientation: MyOrientations = .Landscape

// MARK: - Orientation Methods

override func shouldAutorotate() -> Bool {
    return true

}

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    if self.orientation == .Landscape {
        return UIInterfaceOrientationMask.LandscapeRight
    } else {
        return UIInterfaceOrientationMask.Portrait
    }
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
    if self.orientation == .Landscape {
        return UIInterfaceOrientation.LandscapeRight
    } else {
        return UIInterfaceOrientation.Portrait
    }
}

// Called on region and delegate setters
func refreshOrientation() {
    if let newOrientation = self.delegate?.getOrientation() {
        self.orientation = newOrientation
    }
}

Then when I want to refresh the orientation, I do the following:

// Correct Orientation
let oldOrientation = self.orientation
self.refreshOrientation()
if self.orientation != oldOrientation {
    dispatch_async(dispatch_get_main_queue(), {
        self.orientationRefreshing = true

        let vc = UIViewController()

        UIViewController.attemptRotationToDeviceOrientation()

        self.presentViewController(vc, animated: false, completion: nil)

        UIView.animateWithDuration(0.3, animations: {
            vc.dismissViewControllerAnimated(false, completion: nil)
        })
    })
}

This solution has the side effect of causing view[Will/Did]Appear and view[Will/Did]Disappear to fire all at once. I'm using the local orientationRefreshing variable to manage what aspects of those methods are called again.

like image 50
Nathan Tornquist Avatar answered Oct 19 '22 01:10

Nathan Tornquist


I've encountered this exact problem in the past, myself. I was able to solve it using a simple work around (and GPUImage). My code is in Objective-C but i'm sure you'll have no problem translating it to Swift.

I began by setting the project's supported rotations to all that I hoped to support and then overriding the same UIViewController methods:

-(BOOL)shouldAutorotate { 
    return TRUE; 
}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

Which allows the device to rotate but will persist in Portrait mode. Then began observing for Device rotations:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(adjustForRotation:)
                                             name:UIDeviceOrientationDidChangeNotification
                                           object:nil];

Then updated the UI if the device was in Portrait mode or landscape:

-(void)adjustForRotation:(NSNotification*)notification
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

    switch (orientation) {
        case UIDeviceOrientationLandscapeLeft:
        {
            // UPDATE UI
        }
            break;
        case UIDeviceOrientationLandscapeRight:
        {
            // UPDATE UI
        }
            break;
        default: // All other orientations - Portrait, Upside Down, Unknown
        {
            // UPDATE UI
        }
            break;
    }
} 

And finally, GPUImage rendered the image based on the device's orientation.

[_gpuImageStillCamera capturePhotoAsImageProcessedUpToFilter:last_f
                                              withCompletionHandler:^(UIImage *processedImage, NSError *error) { 
    // Process the processedImage 
}];
like image 3
achi Avatar answered Oct 19 '22 00:10

achi