标签:
引进框架:#import <CoreMotion/CoreMotion.h>
定义属性初始化相关:
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@interface ViewController ()
@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, strong) NSOperationQueue *quene;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化 CMMotionManager
self.motionManager = [[CMMotionManager alloc]init];
// 初始化 NSOperationQueue
self.quene = [[NSOperationQueue alloc]init];
// 调用加速器
[self configureAccelerometer];
// 调用陀螺仪
[self configureGrro];
}每日更新关注:http://weibo.com/hanjunqiang
新浪微博/*
// 每一个设备晃动的时候, 系统通知每一个在用的设备, 可以使本身成为第一响应者
- (BOOL)canBecomeFirstResponder
{
return YES;
}
- (void)viewDidAppear:(BOOL)animated
{
[self becomeFirstResponder];
}
*/
// 加速器的方法
- (void)configureAccelerometer
{
/**
* 5.0之前使用的是pull方式,之后使用push方式
*
// pull 方式
// 判断加速器是否可以使用
if ([_motionManager isAccelerometerAvailable]) {
[_motionManager setAccelerometerUpdateInterval:1 / 40.0];
[_motionManager startAccelerometerUpdates];
}else{
NSLog(@"加速器不能使用");
}
*/
// push 方式
if ([_motionManager isAccelerometerAvailable]) {
// 设置加速器的频率
[_motionManager setAccelerometerUpdateInterval:1 / 40.0];
// 开始采集数据
[_motionManager startAccelerometerUpdatesToQueue:_quene withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
if (fabs(accelerometerData.acceleration.x) > 2.0 || fabs(accelerometerData.acceleration.y) > 2.0 || fabs(accelerometerData.acceleration.z) > 2.0) {
NSLog(@"检测到震动");
}
NSLog(@"%.2f__%.2f__%.2f",accelerometerData.acceleration.x,accelerometerData.acceleration.y,accelerometerData.acceleration.z);
}];
}else{
NSLog(@"加速器不能使用");
}
}
// 触摸结束的时候
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
CMAcceleration acceleration = _motionManager.accelerometerData.acceleration;
NSLog(@"%.2f__%.2f__%.2f",acceleration.x,acceleration.y,acceleration.z);
}
陀螺仪的使用:
// 陀螺仪的使用
- (void)configureGrro
{
if ([_motionManager isGyroAvailable]) {
[self.motionManager startGyroUpdatesToQueue:_quene withHandler:^(CMGyroData *gyroData, NSError *error) {
NSLog(@"%.2f__%.2f__%.2f",gyroData.rotationRate.x,gyroData.rotationRate.y,gyroData.rotationRate.z);
}];
}else{
NSLog(@"陀螺仪不能使用");
}
}- (void)viewDidDisappear:(BOOL)animated
{
[self.motionManager stopAccelerometerUpdates];
[self.motionManager stopGyroUpdates];
}
// 开始晃动的时候触发
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"开始晃动");
}
// 结束晃动的时候触发
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"晃动结束");
}
// 中断晃动的时候触发
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"取消晃动,晃动终止");
}标签:
原文地址:http://blog.csdn.net/qq_31810357/article/details/50124911