I have a question on how to detect the device orientation on iOS. I don't need to receive change notifications, just the current orientation itself. This seems to be a rather simple question, but I haven't been able to wrap my head around it. Below is what I have done so far:
UIDevice *myDevice = [UIDevice currentDevice] ;
[myDevice beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation deviceOrientation = myDevice.orientation;
BOOL isCurrentlyLandscapeView = UIDeviceOrientationIsLandscape(deviceOrientation);
[myDevice endGeneratingDeviceOrientationNotifications];
In my mind this should work. I enable the device to receive device orientation notices, then ask for what orientation it is in, but then it is not working and I don't know why.
UIViewController
has aninterfaceOrientation
property that you can access to find out the current orientation of a view controller.As for your example, that should work. When you say it isn't working, what do you mean? What results does it give you versus what you expected?
Here is some Swift variables to make detection easier:
If you want to get device orientation directly from accelerometer use
[[UIDevice currentDevice] orientation]
. But if you need current orientation of your application(interface orientation) use[[UIApplication sharedApplication] statusBarOrientation]
.Wasn't satisfied by "UIDeviceOrientation" because when a UIViewcontroller orientation is fixed to a specific orientation you don't get a pertinent information with the device orientation, so the right thing to do is using "UIInterfaceOrientation".
You can get the orientation from the UIViewController with a "self.interfaceOrientation", but when you are factorizing our code, you might need to do this kind of test outside a view controller, (custom view, a category…), so you still can access the information anywhere outside the controller by using the rootviewController:
There's a way to achieve this whether the orientation lock is enabled or not by using data from CoreMotion. This is the code:
to get device orientation.
to get device orientation from your app