How to get device current orientation in an App Extension, I have tried below two methods but no success.
It always return UIDeviceOrientationUnknown
[[UIDevice currentDevice] orientation]
It shows red message that ‘sharedApplication’ is not available on iOS (App Extension)
[[UIApplication sharedApplication] statusBarOrientation];
I also add an observer but it not getting called.
[[NSNotificationCenter defaultCenter] addObserver:self.view selector:@selector(notification_OrientationWillChange:) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil]; - (void)notification_OrientationWillChange:(NSNotification*)n { UIInterfaceOrientation orientation = (UIInterfaceOrientation)[[n.userInfo objectForKey:UIApplicationStatusBarOrientationUserInfoKey] intValue]; if (orientation == UIInterfaceOrientationLandscapeLeft) [self.textDocumentProxy insertText:@"Left"]; if (orientation == UIInterfaceOrientationLandscapeRight) [self.textDocumentProxy insertText:@"Right"]; }
So now how can anyone get current device orientation.
I know it's late, but the mistake in this question was in this line:
addObserver:self.view
is wrong, the notification should be attached onself
for being called. Work also on iOS8.I got an idea!
EDIT: On Swift 4 you can do:
The observer method will get called if you add this before:
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
Edit: I use
UIApplicationDidChangeStatusBarOrientationNotification
for the observerAnd in my method I check:
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; BOOL isPortrait = UIDeviceOrientationIsPortrait(orientation);
Edit 2- Xcode 6.2 - iOS 7 & 8
It seems that if you want to use this on both iOS 7 & 8, the code above will give you wrong result on iOS 7.
So I use something else because on iOS 7 the mainScreen's bounds will never change, but on iOS 8 will change if the orientation changes.
I've got 3 macros that will give me the right size of the screen's width & height regardless of the iOS version:
Then, when the notification is fired, i check the orientation like this:
This will work on iOS 7 & iOS 8, but i didn't check for older versions of Xcode, only 6.2
This will return only if the device is on portrait or landscape, not all the 4 orientation types
Use CoreMotion framework can get the device orientation.