CoreMotion(加速计)

时间:2023-03-08 20:35:03

加速计的作用

用于检测设备的运动(比如摇晃)

加速计的经典应用场景

摇一摇

计步器

**********************************

Core Motion获取数据的两种方式

push

实时采集所有数据(采集频率高)

pull

在有需要的时候,再主动去采集数据

 #import "ViewController.h"
#import <CoreMotion/CoreMotion.h> @interface ViewController () @property (strong, nonatomic) CMMotionManager *mgr; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; /* pull方法 */ // 创建加速计管理对象
self.mgr = [[CMMotionManager alloc] init]; // 判断加速计是否可用
if (self.mgr.isAccelerometerAvailable) {
NSLog(@"加速计可用");
// 开始采集(pull) - 这样之后就只会在需要的时候才采集数据, 并放到管理对象的accelerometerData中
[self.mgr startAccelerometerUpdates]; } else {
NSLog(@"加速计不可用");
}
} - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
CMAcceleration acceleration = self.mgr.accelerometerData.acceleration;
NSLog(@"x = %f, y = %f, z = %f", acceleration.x, acceleration.y, acceleration.z);
} /**
* push方式
*/
- (void)push
{
// 创建加速计管理对象
self.mgr = [[CMMotionManager alloc] init]; // 判断加速计是否可用
if (self.mgr.isAccelerometerAvailable) {
NSLog(@"加速计可用");
// 设置采集时间间隔
self.mgr.magnetometerUpdateInterval = / 30.0;
// 开始采集(push)
[self.mgr startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
if (error) return;
// 采集到数据就会调用这个方法
NSLog(@"x = %f, y = %f, z = %f", accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z);
}]; } else {
NSLog(@"加速计不可用");
}
}