iOS日常知识储备

陀螺仪CoreMotion - (Obj-C)

2016-07-14  本文已影响104人  ShenYj

与加速计一样,需要先导入<CoreMotion/CoreMotion.h>头文件,然后创建一个管理者

CoreMotion中获取传感器数据有两种方式
1.Push : 系统主动推送给客户端 实时性强,能耗大
2.Pull : 客户端主要向系统去获取数据 实时性差,能耗小,按需获取

通过是否设置更新间隔来区分,一旦设置了更新间隔,表示使用Push方式,如果使用Pull方式,按需获取,通过管理者的gyroData属性直接得到数据

Push方式:

#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController ()
@property (nonatomic,strong) CMMotionManager *manager;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 创建运动管理者
    self.manager = [[CMMotionManager alloc]init];
    
    // 2. 设置间隔时间
    self.manager.gyroUpdateInterval = 1.0f;
    
    // 3. 开启监测
    [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. 创建运动管理者
    self.manager = [[CMMotionManager alloc]init];
    
    // 2. 开启监测
    [self.manager startGyroUpdates];
}

// 点击屏幕时获取监测数据
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    // 3. 获取监测数据
    CMGyroData *gyroData = self.manager.gyroData;
    CMRotationRate rotationRate = gyroData.rotationRate;
    NSLog(@"%f,%f,%f",rotationRate.x,rotationRate.y,rotationRate.z);
    
}

@end

打印结果:

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
上一篇下一篇

猜你喜欢

热点阅读