1.属性声明
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
@property (nonatomic , strong) CMMotionManager *motionManager;
2.方法实现
weakSelf.motionManager = [[CMMotionManager alloc] init];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
if (weakSelf.motionManager.accelerometerAvailable) {
weakSelf.motionManager.accelerometerUpdateInterval = 1;
[weakSelf.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
if (error) {
[weakSelf.motionManager stopAccelerometerUpdates];
NSLog(@"error");
} else {
// NSLog(@"x 加速度--> %f\n y 加速度--> %f\n z 加速度--> %f\n", accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z);
// 根据 accelerometerData.acceleration.x/y/z来区分手机横竖屏状态。
if (accelerometerData.acceleration.x > accelerometerData.acceleration.y && accelerometerData.acceleration.y < 0) {
NSLog(@"竖屏");
weakSelf.statusStr = @"竖屏";
} else if (accelerometerData.acceleration.x < 0 && accelerometerData.acceleration.y > 0){
NSLog(@"横屏");
weakSelf.statusStr = @"横屏";
} else if (accelerometerData.acceleration.x > 0 && accelerometerData.acceleration.y > 0){
NSLog(@"横屏");
weakSelf.statusStr = @"横屏";
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf.motionManager stopDeviceMotionUpdates];
[weakSelf.motionManager stopAccelerometerUpdates];
});
}
}];
} else {
NSLog(@"This device has no accelerometer");
}