iOS App中调用iPhone各种感应器的方法总结

2020-01-15 16:01:57刘景俊

CoreMotion框架的使用

CoreMotion框架十分强大,它不仅将加速度传感器和螺旋仪传感器进行了统一配置和管理,还为我们封装了许多算法,我们可以直接获取到设备的运动状态信息。

1、CoreMotion负责处理的数据

CoreMotion负责处理四种数据,一种是加速度数据,一种是螺旋仪数据,一种是磁感应数据,还有一种是前三种数据通过复杂运算得到的设备的运动数据。几个主要的类如下:

CMAccelerommterData:设备的加速度数据

typedef struct {
    double x;
    double y;
    double z;
} CMAcceleration;
@interface CMAccelerometerData : CMLogItem
{
@private
    id _internal;
}
//加速度的数据对象
@property(readonly, nonatomic) CMAcceleration acceleration;

@end
CMGyroData:设备的螺旋仪数据

typedef struct {
    double x;
    double y;
    double z; 
} CMRotationRate;
@interface CMGyroData : CMLogItem
{
@private
    id _internal;
}
//螺旋仪数据对象
@property(readonly, nonatomic) CMRotationRate rotationRate;

@end
CMMagnetometerData:磁感应信息

typedef struct {
    double x;
    double y;
    double z;
} CMMagneticField;

@interface CMMagnetometerData : CMLogItem
{
@private
    id _internal;
}

//磁力对象
@property(readonly, nonatomic) CMMagneticField magneticField;

@end


CMDeviceMotion:设备的运动状态数据

@interface CMDeviceMotion : CMLogItem
{
@private
    id _internal;
}
//设备的状态对象
@property(readonly, nonatomic) CMAttitude *attitude;
//设备的角速度
@property(readonly, nonatomic) CMRotationRate rotationRate;
//设备的重力加速度
@property(readonly, nonatomic) CMAcceleration gravity;
//用户嫁给设备的加速度 设备的总加速度为重力加速度叫上用户给的加速度
@property(readonly, nonatomic) CMAcceleration userAcceleration;
//设备的磁场矢量对象
@property(readonly, nonatomic) CMCalibratedMagneticField magneticField NS_AVAILABLE(NA,5_0);
相比之前两个类,这个就比较复杂了,attitude对象中又封装了许多设备的状态属性:

@interface CMAttitude : NSObject <NSCopying, NSSecureCoding>
{
@private
    id _internal;
}
//设备的欧拉角roll
@property(readonly, nonatomic) double roll;