iOS之 CoreMotion 框架
2015-10-30 10:50
337 查看
在项目中经常会使用到重力加速度,陀螺仪,最近在一个项目中使用到了CoreMotion 框架,需求是:上下摇摆手机控制智能椅子的角度调节,该项目是使用蓝牙4.0进行通讯的,在iOS 内已经封装好了CoreBluetooth 框架,不过需要iPHone4s 以上的手机,和iPad min 以上的平板电脑才有蓝牙4.0. 今天在这里先记录一下CoreMotion 框架的使用. 主要的类:CMMotionManager , NSOperationQueue. 下面是一个被我封装过的一个类。 项目需要导入CoreMotion.Framework 在.h 文件需要#import <CoreMotion/CoreMotion.h> .h文件代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 #import <Foundation/Foundation.h> #import <CoreMotion/CoreMotion.h> typedef enum _MotionDirection {UNKNOWDIRECTION=0,UP,DOWN}MotionDirection; @interface iCtrlCMManager : NSObject @property (nonatomic,retain) CMMotionManager * ictrlCMManager; @property (nonatomic,assign) MotionDirection motionDirection; +(id)sharedInstance; -(void)startMotion; -(void)stopMotion; @end .m文件代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 #import "iCtrlCMManager.h" @implementation iCtrlCMManager #pragma mark - #pragma mark life cycle +(id)sharedInstance { static iCtrlCMManager *this = nil; if(!this) { this = [[iCtrlCMManager alloc] init]; } return this; } -(id)init { self = [super init]; if(self) { _ictrlCMManager = [[CMMotionManager alloc] init]; } return self; } -(void)dealloc { [_ictrlCMManager release]; [super dealloc]; } #pragma mark #pragma mark instance methods -(void)startMotion { _motionDirection = UNKNOWDIRECTION; if(_ictrlCMManager.accelerometerAvailable) { NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; _ictrlCMManager.accelerometerUpdateInterval = 1.0/60.0; __block float y = 0.0; __block int i = 0; [_ictrlCMManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) { if (error) { NSLog(@"CoreMotion Error : %@",error); [_ictrlCMManager stopAccelerometerUpdates]; } if(i == 0) { y = accelerometerData.acceleration.y; } i++; if(fabs(y - accelerometerData.acceleration.y) > 0.4) { if(y > accelerometerData.acceleration.y) { NSLog(@"UP"); _motionDirection = UP; } else { NSLog(@"Down"); _motionDirection = DOWN; } y = accelerometerData.acceleration.y; } }]; } else { NSLog(@"The accelerometer is unavailable"); } } -(void)stopMotion { _motionDirection = UNKNOWDIRECTION; [_ictrlCMManager stopAccelerometerUpdates]; } @end
相关文章推荐
- iOS开发中的Git流程
- 整理 iOS 9 适配中出现的坑(图文)
- iOS测试(一)
- iOS拨打电话的三种方法
- iOS 9之适配ATS
- iOS之内存管理---堆栈问题详解
- IOS基础:retain,copy,assign及autorelease
- 集成Reveal:不修改您的Xcode工程并加载Reveal
- 分享一个iOS下实现基本绘画板功能的简单方法
- github优秀开源项目大全-iOS
- ios 发布相关材料记录
- IOS之同步请求、异步请求、GET请求、POST请求
- iOS9之新特性
- iOS 9.1 深坑体验及其破解之道
- iOS 上传注意小事项
- iOS应用开发视频教程笔记(十六)Action Sheets, Image Picker, Core Motion
- 关于ios上应用版本更新的一些小结
- iOS 基础类解析 - NSString
- iOS 第三方使用常规流程
- iOS 开发:上拉加载,下拉刷新