UIAccelerometer在iOS 5中已经过期,iOS 4以后使用CoreMotion.framework
不只包含加速计,是一个对传感器统一管理的框架
需要先导入<CoreMotion/CoreMotion.h>头文件,然后创建一个管理者
CoreMotion中获取传感器数据有两种方式
1.Push : 系统主动推送给客户端 实时性强,能耗大
2.Pull : 客户端主要向系统去获取数据 实时性差,能耗小,按需获取
通过是否设置更新间隔来区分,一旦设置了更新间隔,表示使用Push方式,如果使用Pull方式,按需获取,通过管理者的accelerometerData属性直接得到数据
Push方式,示例代码:
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
// 运动管理者
@property (nonatomic,strong) CMMotionManager *manager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建运动管理者 (因为检测操作是一个耗时操作,实时回调,所以需要一个强引用)
self.manager = [[CMMotionManager alloc]init];
// 设置更新间隔
self.manager.accelerometerUpdateInterval = 1.0f;
// 开启监测
[self.manager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
CMAcceleration acceleration = accelerometerData.acceleration;
NSLog(@"%f, %f, %f",acceleration.x, acceleration.y, acceleration.z);
}];
}
@end
Pull方式,示例代码:
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
// 运动管理者
@property (nonatomic,strong) CMMotionManager *manager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建运动管理者 (因为检测操作是一个耗时操作,实时回调,所以需要一个强引用)
self.manager = [[CMMotionManager alloc]init];
// 开启监测
[self.manager startAccelerometerUpdates];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// 最新的采样数据
CMAccelerometerData *accelerometerData = self.manager.accelerometerData;
CMAcceleration acceleration = accelerometerData.acceleration;
NSLog(@"%f, %f, %f",acceleration.x, acceleration.y, acceleration.z);
}
@end