Disclaimer: This article is a blogger original article, reproduced, please indicate the source of the article. https://blog.csdn.net/SunFlowerInRain/article/details/78847740
Start by adding CoreMotion.frameWork framework
Basic configuration information in the code
#import <CoreMotion/CoreMotion.h>
// 创始化状态,添加Queue来检测状态
- (void)startMotionManager{
if (_cmotionManager == nil) {
_cmotionManager = [[CMMotionManager alloc] init];
}
_cmotionManager.deviceMotionUpdateInterval = 1/15.0;
if (_cmotionManager.deviceMotionAvailable) {
NSLog(@"Device Motion Available");
[_cmotionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
[self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
}];
}}
// detector gyroscope according to the current state, the rotation direction determination screen
- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
double x = deviceMotion.gravity.x;
double y = deviceMotion.gravity.y;
if (fabs(y) >= fabs(x))
{
if (y >= 0){
orientation = UIDeviceOrientationPortraitUpsideDown;
}
else{
orientation= UIDeviceOrientationPortrait;
}
}
else
{
if (x >= 0){
orientation= UIDeviceOrientationLandscapeRight;
}
else{
orientation= UIDeviceOrientationLandscapeLeft;
}
}
}
After completion
// Remove listening dealloc method
- (void) dealloc {
[_cmotionManager stopDeviceMotionUpdates];
}