#import <CoreMotion/CoreMotion.h> //!!!!!!
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *leftRightLabel;
@property (weak, nonatomic) IBOutlet UILabel *upDownLabel;
@property (weak, nonatomic) IBOutlet UILabel *rollLabel;
@property (weak, nonatomic) IBOutlet UILabel *addX;
@property (weak, nonatomic) IBOutlet UILabel *addY;
@property (weak, nonatomic) IBOutlet UILabel *addZ;
@property (weak, nonatomic) IBOutlet UILabel *gravityX;
@property (weak, nonatomic) IBOutlet UILabel *gravityY;
@property (weak, nonatomic) IBOutlet UILabel *gravityZ;
@property (weak, nonatomic) IBOutlet UILabel *rotationRateX;
@property (weak, nonatomic) IBOutlet UILabel *rotationRateY;
@property (weak, nonatomic) IBOutlet UILabel *rotationRateZ;
/**
* 运动管理器
*/
@property (nonatomic, strong) CMMotionManager *motionManager;
#pragma mark 开关按钮点击事件 拖一个switch控件
-(IBAction)motionSwitchHandler:(UISwitch *)sender {
if (sender.on) {
//如果是开启的就调用方法 开启并测试
[self controlHardware];
} else {
//否则就停掉感应器
[self.motionManager stopDeviceMotionUpdates];
}
}
#pragma mark 控制设备管理器的开启
- (void)controlHardware {
//开启
//当前队列, 当前线程
//实时返回数据
if ([self.motionManager isDeviceMotionAvailable]) { //判断该设备是否有传感器
if ([self.motionManager isDeviceMotionActive]) { //判断传感器是否已开启
} else {
[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
//左右摇摆, 仰俯, 滚动
self.leftRightLabel.text = [NSString stringWithFormat:@"左右摇摆: %.2f", motion.attitude.yaw];
self.upDownLabel.text = [NSString stringWithFormat:@"仰俯: %.2f", motion.attitude.pitch];
self.rollLabel.text = [NSString stringWithFormat:@"滚动: %.2f", motion.attitude.roll];
//加速度
self.addX.text = [NSString stringWithFormat:@"加速度x: %.2f", motion.userAcceleration.x];
self.addY.text = [NSString stringWithFormat:@"加速度y: %.2f", motion.userAcceleration.y];
self.addZ.text = [NSString stringWithFormat:@"加速度z: %.2f", motion.userAcceleration.z];
//重力感应
self.gravityX.text = [NSString stringWithFormat:@"重力感应x: %.2f", motion.gravity.x];
self.gravityY.text = [NSString stringWithFormat:@"重力感应y: %.2f", motion.gravity.y];
self.gravityZ.text = [NSString stringWithFormat:@"重力感应z: %.2f", motion.gravity.z];
//陀螺仪
self.rotationRateX.text = [NSString stringWithFormat:@"自转速率x: %.2f", motion.rotationRate.x];
self.rotationRateY.text = [NSString stringWithFormat:@"自转速率y: %.2f", motion.rotationRate.y];
self.rotationRateZ.text = [NSString stringWithFormat:@"自转速率z: %.2f", motion.rotationRate.z];
}];
}
}
//停掉
// [self.motionManager stopDeviceMotionUpdates];
}
<pre name="code" class="objc">