@interface ViewController ()
@property (strong, nonatomic) CMMotionManager *motionManager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self startDeviceMotionUpdates];
}
- (void)startDeviceMotionUpdates {
if (!_motionManager) {
_motionManager = [[CMMotionManager alloc] init];
_motionManager.deviceMotionUpdateInterval = 1/3.f;
}
if (_motionManager.deviceMotionAvailable) {
[_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
[self handleDeviceMotion:motion];
}];
}
}
- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion {
double x = deviceMotion.gravity.x;
double y = deviceMotion.gravity.y;
if (fabs(y) >= fabs(x)) {
if (y >= 0) {
NSLog(@"Down");
} else {
NSLog(@"Portrait");
}
} else {
if (x >= 0) {
NSLog(@"Right");
} else {
NSLog(@"Left");
}
}
}
- (void)dealloc {
[_motionManager stopDeviceMotionUpdates];
}
@end