I have a view controller which is always in portrait. There is a certain feature which works according to the current orientation of the device itself, not orientation of the view controller.
How could I detect the device's orientation and trigger function on orientation changed in this case?
Asked
Active
Viewed 127 times
0

Vinh Hung Nguyen
- 139
- 1
- 11
-
Do you mean you want to know which way gravity is, relative to the device? You can try using [`CMMotionManager.startDeviceMotionUpdates`](https://developer.apple.com/documentation/coremotion/cmmotionmanager/1616048-startdevicemotionupdates), and get `gravity` from it, which is a 3D vector. – Sweeper Sep 08 '21 at 08:18
-
you can achieve this by running CMMotionManager. [try this answer](https://stackoverflow.com/questions/49164302/get-current-ios-device-orientation-even-if-devices-orientation-locked) – MemetGhini Sep 08 '21 at 11:49
2 Answers
0
Since iOS 8 they introduced viewWillTransitionToSize
that's triggered every time the rotation happens
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
// do what you need with orientation here
} completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
}];
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}

Alastar
- 1,284
- 1
- 8
- 14
0
you can achieve this by running CMMotionManager
#import <CoreMotion/CoreMotion.h>
#define DEGREES(x) (180.0 * x / M_PI)
#define RADIAN(x) (M_PI*x/180.0)
#define UPDATE_INTERVAL 0.3
typedef struct Point3D {
CGFloat x, y, z;
} Point3D;
@interface DirectionListener()
{
NSTimer * _motionTimer;
CMMotionManager *_motionManager;
}
@end
@implementation DirectionListener
- (instancetype)init
{
self = [super init];
if (self)
{
}
return self;
}
- (void)dealloc
{
[self stopListenning];
_motionManager = nil;
if (_motionTimer)
{
[_motionTimer invalidate];
_motionTimer = nil;
}
}
- (void)startListenning
{
if (_motionManager.deviceMotionActive)
{
return;
}
if (!_motionManager)
{
_motionManager = [[CMMotionManager alloc] init];
_motionManager.deviceMotionUpdateInterval = UPDATE_INTERVAL;
}
[_motionManager startDeviceMotionUpdates];
if (!_motionTimer)
{
_motionTimer = [NSTimer scheduledTimerWithTimeInterval:UPDATE_INTERVAL target:self selector:@selector(changeWithAttitude) userInfo:nil repeats:YES];
}
}
- (void)stopListenning {
if (_motionManager.deviceMotionActive)
{
[_motionManager stopDeviceMotionUpdates];
[_motionTimer invalidate];
_motionTimer = nil;
}
}
-(void)changeWithAttitude
{
//get the value from motionManager there
}

MemetGhini
- 31
- 5