Core Motion 加速器的使用步骤

来源:互联网 发布:洛奇英雄传n卡优化 编辑:程序博客网 时间:2024/04/30 16:50


两种使用方法

1. pull(用户主动获取,调用频率根据用户需求)

- (void)pull

{

    // 1. 创建mgr

    CMMotionManager *mgr = [[CMMotionManageralloc] init];

    _mgr = mgr; 

    

    // 2. 判断加速器是否能够使用

    if (mgr.isAccelerometerAvailable) {// 可以使用

        //  3.开始获取

        [mgr startAccelerometerUpdates];

        

        // 此处已点击一次屏幕采集一次信息

    }

    

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    // 点击屏幕就获取采集信息

    NSLog(@"x = %f y = %f z = %f ",_mgr.accelerometerData.acceleration.x ,_mgr.accelerometerData.acceleration.y,_mgr.accelerometerData.acceleration.z);

}


--------------------------- 华丽的分割线-----------------------


2. push (系统主动推送,调用频率高)

- (void)push

{

    // 1.创建CoreMotion管理者

    CMMotionManager *mgr = [[CMMotionManageralloc] init];

    _mgr = mgr;

    

    // 2.判断加速器是否能够使用(最好判断)

    if(mgr.isAccelerometerAvailable){// 可以使用

        

        // 3.设置获取时间间隙

        mgr.accelerometerUpdateInterval = 1.0 / 30.0;// 1分钟30

        

        // 4.开始获取

        [mgr startAccelerometerUpdatesToQueue:[NSOperationQueuemainQueue] withHandler:^(CMAccelerometerData *_Nullable accelerometerData, NSError * _Nullable error) {

            if (!error) {// 采集成功

                NSLog(@"x = %f y = %f z = %f ", accelerometerData.acceleration.x , accelerometerData.acceleration.y, accelerometerData.acceleration.z);

            }

        }];

    }

}

@end



1 0