磁力计CoreMotion - (Obj-C)

磁力计用来检测地球磁场,与加速计、陀螺仪一样,需要先导入头文件,然后创建一个管理者
获取传感器数据同样有两种方式
1.Push : 系统主动推送给客户端 实时性强,能耗大
2.Pull : 客户端主要向系统去获取数据 实时性差,能耗小,按需获取

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

Push方式:

#import "ViewController.h"
#import 


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

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 创建管理者
    self.manager = [[CMMotionManager alloc]init];
    
    // 2. 设置间隔时间(频率)
    self.manager.magnetometerUpdateInterval = 1.0f;
    
    // 3. 开启监测
    [self.manager startMagnetometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMMagnetometerData * _Nullable magnetometerData, NSError * _Nullable error) {
        
        CMMagneticField magneticField = magnetometerData.magneticField;
        NSLog(@"%f,%f,%f",magneticField.x,magneticField.y,magneticField.z);
        
    }];
    
}


@end

Pull方式:

#import "ViewController.h"
#import 


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

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 创建管理者
    self.manager = [[CMMotionManager alloc]init];
    
    // 2. 开启监测
    [self.manager startMagnetometerUpdates];
    
}

// 3. 点击屏幕获取数据
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    CMMagnetometerData *magnetometerData = self.manager.magnetometerData;
    CMMagneticField magneticField = magnetometerData.magneticField;
    NSLog(@"%f,%f,%f",magneticField.x,magneticField.y,magneticField.z);
}


@end

打印结果:

2016-07-14 19:04:47.312 04-磁力计[4348:4672749] 48.842041,33.977066,-246.741608
2016-07-14 19:04:48.309 04-磁力计[4348:4672749] 50.080780,34.154037,-246.571686
2016-07-14 19:04:49.670 04-磁力计[4348:4672749] 51.673462,34.684921,-246.741608
2016-07-14 19:04:50.668 04-磁力计[4348:4672749] 50.788635,32.384384,-247.251404
2016-07-14 19:04:51.666 04-磁力计[4348:4672749] 44.417938,23.182266,-244.532501

你可能感兴趣的:(磁力计CoreMotion - (Obj-C))