views:

25

answers:

2

In my iPhone app I need to detect the current orientation and I have to determine if I'm in portrait or landscape. I use this code:

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
     NSLog(@"portrait");
     ...
} else {
     NSLog(@"landscape");
     ...
}

Everything is ok when my iPhone is in my hand. But when i put it on the table and i run the application, the content is displayed on the screen in portrait mode and my code goes to else and NSLog prints landscape.

Is my test incomplete ? How to prevent this case ?

EDIT : the test is performed in my controller viewDidLoad method and my application handle rotation.

+2  A: 

UIDevice.orientation is of type UIDeviceOrientation, which is a superset of UIInterfaceOrientation. You are probably getting the value UIDeviceOrientationFaceUp.

This underscores that yes, your test is incomplete. You should write something like this:

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
     NSLog(@"portrait");
     ...
} else if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
     NSLog(@"landscape");
     ...
} else {
     NSLog(@"WTF? %d", orientation);
     assert(false);
}

Then, you'll know if you if you've missed something.

Marcelo Cantos
what do you mean, i'm not sure to understand how it can help for my problem ?
lefakir
@lefakir: The device is telling you that it is flat on its back. Read @par's answer.
Marcelo Cantos
+1  A: 

UIDevice.orientation can return that the device is flat or upside down (not inverted portrait, upside-down as in laying on its face). Instead call UIViewController.interfaceOrientation on your root view controller.

par
your response is also right but Marcelo Cantos answered first even if it wasn'nt really well explained (from my point of view) in the first version
lefakir
I'm good, but really for interface orientation you should not use [UIDevice currentDevice].orientation. Rather in your main UIViewController query the interfaceOrientation property (see UIViewController.h). That method always returns either portrait or landscape and never the face up/down constants so it is probably more likely what you are really interested in knowing (i.e. whether you're in portrait or landscape).
par