@import CoreMotion;
@property (nonatomic,strong)CMMotionManager *motionManager;
-(void)starMotionManager{
if (_motionManager == nil) {
_motionManager = [CMMotionManager new];
}
if (_motionManager.deviceMotionAvailable) {
[_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
[self handleDeviceMotion:motion];
}];
}
}
-(void)handleDeviceMotion:(CMDeviceMotion *)motion{
double x = motion.gravity.x;
double y = motion.gravity.y;
if (fabs(y)>=fabs(x)) {
if (y>=0) {
// UIDeviceOrientationPortraitUpsideDown
NSLog(@"头向下");
}else{
// UIDeviceOrientationPortrait
NSLog(@"竖屏");
}
}else{
if (x >= 0) {
// UIDeviceOrientationLandscapeRight
NSLog(@"头向右");
}else{
// UIDeviceOrientationLandscapeLef
NSLog(@"头向左");
}
}
}
// 在适当的位置启动重力引擎
[self starMotionManager];
// 停止重力引擎