磁力计

同样包含在CoreMotion框架中

  • push采样
#import "ViewController.h"
#import 
@interface ViewController ()
/** 运动管理者*/
@property (nonatomic, strong) CMMotionManager *mgr;
@end

@implementation ViewController
- (CMMotionManager *)mgr
{
    if (!_mgr) {
        _mgr = [[CMMotionManager alloc]init];
    }
    return _mgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //判断磁力计是否可用
    if (!self.mgr.isMagnetometerAvailable) {
        NSLog(@"磁力计不可用");
        return;
    }
    //设置采样间隔
    self.mgr.magnetometerUpdateInterval = 0.3;
    //开始采样
    [self.mgr startMagnetometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMMagnetometerData * _Nullable magnetometerData, NSError * _Nullable error) {
        if (error) {
            NSLog(@"采样出错");
            return ;
        }
        CMMagneticField magneticField = magnetometerData.magneticField;
        NSLog(@"x:%f y:%f z:%f",magneticField.x,magneticField.y,magneticField.z);
    }];
}

@end

  • pull采样
#import "ViewController.h"
#import 
@interface ViewController ()
/** 运动管理者*/
@property (nonatomic, strong) CMMotionManager *mgr;
@end

@implementation ViewController
- (CMMotionManager *)mgr
{
    if (!_mgr) {
        _mgr = [[CMMotionManager alloc]init];
    }
    return _mgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //判断磁力计是否可用
    if (!self.mgr.isMagnetometerAvailable) {
        NSLog(@"磁力计不可用");
        return;
    }
    //开始采样
    [self.mgr startMagnetometerUpdates];
    //获取采样数据
    CMMagnetometerData *magnetometerData = self.mgr.magnetometerData;
    CMMagneticField magneticField = magnetometerData.magneticField;
    NSLog(@"x:%f y:%f z:%f",magneticField.x,magneticField.y,magneticField.z);
}

@end

你可能感兴趣的:(磁力计)