CoreMotion(加速计)

加速计的作用

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

加速计的经典应用场景

摇一摇

计步器

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

Core Motion获取数据的两种方式

push

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

 pull

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

 1 #import "ViewController.h"
 2 #import <CoreMotion/CoreMotion.h>
 3 
 4 @interface ViewController ()
 5 
 6 @property (strong, nonatomic) CMMotionManager *mgr;
 7 
 8 @end
 9 
10 @implementation ViewController
11 
12 - (void)viewDidLoad {
13     [super viewDidLoad];
14     
15     /* pull方法 */
16     
17     // 创建加速计管理对象
18     self.mgr = [[CMMotionManager alloc] init];
19     
20     // 判断加速计是否可用
21     if (self.mgr.isAccelerometerAvailable) {
22         NSLog(@"加速计可用");
23         // 开始采集(pull) - 这样之后就只会在需要的时候才采集数据, 并放到管理对象的accelerometerData中
24         [self.mgr startAccelerometerUpdates];
25         
26     } else {
27         NSLog(@"加速计不可用");
28     }
29 }
30 
31 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
32 {
33     CMAcceleration acceleration = self.mgr.accelerometerData.acceleration;
34     NSLog(@"x = %f, y = %f, z = %f", acceleration.x, acceleration.y, acceleration.z);
35 }
36 
37 /**
38  *  push方式
39  */
40 - (void)push
41 {
42     // 创建加速计管理对象
43     self.mgr = [[CMMotionManager alloc] init];
44     
45     // 判断加速计是否可用
46     if (self.mgr.isAccelerometerAvailable) {
47         NSLog(@"加速计可用");
48         // 设置采集时间间隔
49         self.mgr.magnetometerUpdateInterval = 1 / 30.0;
50         // 开始采集(push)
51         [self.mgr startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
52             if (error) return;
53             // 采集到数据就会调用这个方法
54             NSLog(@"x = %f, y = %f, z = %f", accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z);
55         }];
56         
57     } else {
58         NSLog(@"加速计不可用");
59     }
60 }
原文地址:https://www.cnblogs.com/Rinpe/p/4755218.html