與加速計一樣,需要先導(dǎo)入<CoreMotion/CoreMotion.h>頭文件,然后創(chuàng)建一個管理者
CoreMotion中獲取傳感器數(shù)據(jù)有兩種方式
1.Push : 系統(tǒng)主動推送給客戶端 實時性強,能耗大
2.Pull : 客戶端主要向系統(tǒng)去獲取數(shù)據(jù) 實時性差,能耗小,按需獲取
通過是否設(shè)置更新間隔來區(qū)分,一旦設(shè)置了更新間隔,表示使用Push方式,如果使用Pull方式,按需獲取,通過管理者的gyroData屬性直接得到數(shù)據(jù)
Push方式:
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
@property (nonatomic,strong) CMMotionManager *manager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 創(chuàng)建運動管理者
self.manager = [[CMMotionManager alloc]init];
// 2. 設(shè)置間隔時間
self.manager.gyroUpdateInterval = 1.0f;
// 3. 開啟監(jiān)測
[self.manager startGyroUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMGyroData * _Nullable gyroData, NSError * _Nullable error) {
CMRotationRate rotationRate = gyroData.rotationRate;
NSLog(@"%f,%f,%f",rotationRate.x,rotationRate.y,rotationRate.z);
}];
}
@end
Pull方式:
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
@property (nonatomic,strong) CMMotionManager *manager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 創(chuàng)建運動管理者
self.manager = [[CMMotionManager alloc]init];
// 2. 開啟監(jiān)測
[self.manager startGyroUpdates];
}
// 點擊屏幕時獲取監(jiān)測數(shù)據(jù)
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
// 3. 獲取監(jiān)測數(shù)據(jù)
CMGyroData *gyroData = self.manager.gyroData;
CMRotationRate rotationRate = gyroData.rotationRate;
NSLog(@"%f,%f,%f",rotationRate.x,rotationRate.y,rotationRate.z);
}
@end
打印結(jié)果:
2016-07-14 18:54:42.893 03-陀螺儀[4338:4669017] -0.849916,2.210453,0.640329
2016-07-14 18:54:43.305 03-陀螺儀[4338:4669017] 4.547867,-4.541954,-1.075862
2016-07-14 18:54:43.621 03-陀螺儀[4338:4669017] -7.368330,10.033870,2.520494
2016-07-14 18:54:44.039 03-陀螺儀[4338:4669017] -1.995928,-0.730891,-0.609648
2016-07-14 18:54:44.256 03-陀螺儀[4338:4669017] 4.259613,-2.782650,-0.929494
2016-07-14 18:54:44.505 03-陀螺儀[4338:4669017] 2.903455,-3.432033,-0.955542
2016-07-14 18:54:44.722 03-陀螺儀[4338:4669017] -1.869434,1.511082,-0.031730
2016-07-14 18:54:44.888 03-陀螺儀[4338:4669017] -0.701699,0.812793,-0.336599