#import "ViewController.h"
// 处理设备的动作相关的事件
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
// 使用动作事件的入口
@property (strong, nonatomic) CMMotionManager *motionManager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// accelerometer 加速计
// 有两获取数据的方式, Pull(主动获取),
self.motionManager = [[CMMotionManager alloc] init];
// 获取硬件数据的更新间隙
self.motionManager.accelerometerUpdateInterval = 0.5;
}
#pragma mark - Pull
- (IBAction)startBtnAction:(id)sender
{
// isAccelerometerActive 判断加速计是否已经激活
if (self.motionManager.isAccelerometerActive == NO) {
// 开始更新硬件数据
[self.motionManager startAccelerometerUpdates];
}
}
- (IBAction)pullBtnAction:(id)sender
{
// 获取硬件数据, 会保存在属性当中
CMAccelerometerData *data = [self.motionManager accelerometerData];
CMAcceleration acceleration = data.acceleration;
NSLog(@"%f, %f, %f", acceleration.x, acceleration.y, acceleration.z);
}
- (IBAction)stopBtnAction:(id)sender
{
if (self.motionManager.isAccelerometerActive == YES) {
// 结束更新硬件数据
[self.motionManager stopAccelerometerUpdates];
}
}
#pragma mark - Push
- (void)pushTest
{
// 1. 判断是否支持加速计硬件
BOOL available = [self.motionManager isAccelerometerAvailable];
if (available == NO) {
NSLog(@"加速计不能用");
return;
}
// Push(按照accelerometerUpdateInterval定时推送回来)
[self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
// CMAcceleration 是表示加速计数据的结构体
CMAcceleration acceleration = accelerometerData.acceleration;
NSLog(@"%f, %f, %f", acceleration.x, acceleration.y, acceleration.z);
}];
// 结束获取硬件数据
[self.motionManager stopAccelerometerUpdates];
}
@end