iOS 加速计 摇一摇

第一种加速计 准确判断手机晃动
#import <CoreMotion/CoreMotion.h> 框架 里面有一个 CMMotionManager *_manager;
@property(assign, nonatomic) NSTimeInterval accelerometerUpdateInterval //加速计的计算时间

startAccelerometerUpdates
初始化CMMotionManager管理对象
调用管理对象的对象方法获取数据,有2种方式
处理数据
当你不需要使用的时候,停止获取数据
-(void)stopAccelerometerUpdates;//停止获取加速度计数据
- (void)startAccelerometerUpdates //开始获取加速计的数据
- (void)stopDeviceMotionUpdates //也是停止获取数据
-(void)startAccelerometerUpdatesToQueue:(NSOperationQueue*)queuewithHandler:(CMAccelerometerHandler)handler __TVOS_PROHIBITED; //开启获取加速计的数据 带有block 将 CMMotionManager加到队列中 避免数据并发性

废话不多说直接上代码

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
_manager = [[CMMotionManager alloc]init];
_manager.accelerometerUpdateInterval = 0.1;
WEAKSELF
[_manager startAccelerometerUpdatesToQueue:operationQueue withHandler:^(CMAccelerometerData *latestAcc, NSError *error) {
    dispatch_sync(dispatch_get_main_queue(), ^(void) {
        // 所有操作进行同步
        @synchronized(_manager) {
            //在这里进行摇动后的操作
            [self confgStr];
        };
    });
}];

这是晃动是判断的三个轴
这里写图片描述

- (void)confgStr {
//判断晃动的频率
if (fabs(_manager.accelerometerData.acceleration.x) > 6.0 || fabs(_manager.accelerometerData.acceleration.y) > 6.0 ||fabs(_manager.accelerometerData.acceleration.z) > 6.0) {
            if (_isAdd) {
    //            [NSThread sleepForTimeInterval:0.3];
                [[EMCDDeviceManager sharedInstance] playVibration];
                NSString *str = _centerLabel.text;
                _shakeNumber = _centerLabel.text = [NSString stringWithFormat:@"%ld",[str integerValue] + 1];
            }
        }
}

**第二种 系统自带摇一摇

// 设置允许摇一摇功能
[UIApplication sharedApplication].applicationSupportsShakeToEdit = YES;  
// 并让自己成为第一响应者
[self becomeFirstResponder];  
//开始摇动
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
//摇动结束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
//摇动被打断 比如打电话 系统等方法打断
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);

猜你喜欢

转载自blog.csdn.net/goods_boy/article/details/70240848