iOS开发实录iOS OC 学习手册iOS Developer

iOS 传感器

2017-03-08  本文已影响49人  _YZG_

目录
一、距离传感器
二、加速计
三、磁力计、陀螺仪的使用和上述加速计的使用步骤类似
四、摇一摇
五、步数

一、距离传感器

[UIDevice currentDevice].proximityMonitoringEnabled = YES;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [UIDevice currentDevice].proximityMonitoringEnabled = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
}
- (void)proximityStateDidChange
{
    if ([UIDevice currentDevice].proximityState) {
        NSLog(@"有物品靠近");
    } else {
        NSLog(@"有物品远离");
    }
}

二、加速计

加速计.png

Core Moton 获取数据的两种方式:

1)push方式

实例程序:

#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController ()

@property (nonatomic, strong) CMMotionManager *mgr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 判断加速计是否好用
    if (!self.mgr.isAccelerometerAvailable) {
        NSLog(@"加速计不好用");
        return;
    }
    // 2. 设置采样间隔
    self.mgr.accelerometerUpdateInterval = 1.0 / 30.0; // 1秒钟采样30次
    
    // 3. 开始采样
    [self.mgr startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
        // 当采样到加速计信息时就会执行
        if (error) return;
        
        // 4.获取加速计信息
        CMAcceleration acceleration = accelerometerData.acceleration;
        NSLog(@"x:%f y:%f z:%f", acceleration.x, acceleration.y, acceleration.z);
    }];
    
   
}

- (CMMotionManager *)mgr
{
    if (!_mgr) {
        _mgr = [[CMMotionManager alloc] init];
    }
    return _mgr;
}
@end
2)pull方式
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>

@interface ViewController ()

@property (nonatomic, strong) CMMotionManager *mgr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 判断加速计是否好用
    if (!self.mgr.isAccelerometerAvailable) {
        NSLog(@"加速计不好用");
        return;
    }
   // 2. 开始采样
   [self.mgr startAccelerometerUpdates];

}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    CMAcceleration acceleration = self.mgr.accelerometerData.acceleration;
    NSLog(@"x:%f y:%f z:%f", acceleration.x, acceleration.y, acceleration.z);
}

- (CMMotionManager *)mgr
{
    if (!_mgr) {
        _mgr = [[CMMotionManager alloc] init];
    }
    return _mgr;
}

@end

三、磁力计、陀螺仪的使用和上述加速计的使用步骤类似

不同点:

@property(readonly, nonatomic, getter=isAccelerometerAvailable) BOOL accelerometerAvailable;

陀螺仪

@property(readonly, nonatomic, getter=isGyroAvailable) BOOL gyroAvailable;

磁力计

@property(readonly, nonatomic, getter=isMagnetometerAvailable) BOOL magnetometerAvailable
@property(assign, nonatomic) NSTimeInterval accelerometerUpdateInterval;

陀螺仪

@property(assign, nonatomic) NSTimeInterval gyroUpdateInterval;

磁力计

@property(assign, nonatomic) NSTimeInterval magnetometerUpdateInterval
- (void)startAccelerometerUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMAccelerometerHandler)handler;

陀螺仪

- (void)startGyroUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMGyroHandler)handler;

磁力计

- (void)startMagnetometerUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMMagnetometerHandler)handler;
- (void)startAccelerometerUpdates;

陀螺仪

- (void)startGyroUpdates;

磁力计

- (void)startMagnetometerUpdates;
CMAcceleration acceleration = self.mgr.accelerometerData.acceleration;
NSLog(@"x:%f y:%f z:%f", acceleration.x, acceleration.y, acceleration.z);

陀螺仪

CMRotationRate rate = self.mgr.gyroData.rotationRate;
NSLog(@"x:%f y:%f z:%f", rate.x, rate.y, rate.z);

磁力计

CMMagneticField magneticField = self.mgr.magnetometerData.magneticField;
    NSLog(@"x:%f y:%f z:%f",magneticField.x, magneticField.y, magneticField.z);

还有个停止方法

// 加速计、陀螺仪、磁力计都类似
- (void)stopAccelerometerUpdates

四、摇一摇


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}
- (void) viewWillAppear:(BOOL)animated
{
    [self resignFirstResponder];
    [super viewWillAppear:animated];    
}
/*
解释一下
在自定义的UIView子类中,需要实现canBecomeFirstResponder方法,并返回YES(默认返回FALSE),
才可使becomeFirstResponder可返回YES,才可使其成为第一响应者,即接受第一响应者状态。

一个响应者只有当当前响应者可以取消第一响应者状态 (canResignFirstResponder) 并且新的响应者可以成为第一响应者时,才可以成为第一响应者。
*/
-(BOOL)canBecomeFirstResponder 
{
    return YES;
}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{

    if (motion == UIEventSubtypeMotionShake) {
        NSLog(@"摇一摇"); 
    }    
}

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"摇一摇被取消");
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"摇一摇停止");
}

模拟器中摇一摇动作

摇一摇.png

五、步数

if (![CMPedometer isStepCountingAvailable]) {
      NSLog(@"计步器不可用");
      return;
  }
CMPedometer *stepCounter = [[CMPedometer alloc] init];
 [stepCounter startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData *pedometerData, NSError *error) {
      if (error) return;
      // 4.获取采样数据,实时走
      NSLog(@"steps = %@", pedometerData.numberOfSteps);
  }];

统计今天走了多少步,多远,垂直,室内导航等
http://www.jianshu.com/p/e5f332f9b27c
还可通过HealthKit框架获取今日步数, 参考以下链接
http://www.jianshu.com/p/913013a226aa

        NSDate *now = [NSDate date];
        NSCalendar *calender = [NSCalendar currentCalendar];
        NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        NSDateComponents *dateComponent = [calender components:unitFlags fromDate:now];
        int hour = (int)[dateComponent hour];
        int minute = (int)[dateComponent minute];
        int second = (int)[dateComponent second];
        NSDate *nowDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second) ];
        NSDate *nextDay = [NSDate dateWithTimeIntervalSinceNow:  - (hour*3600 + minute * 60 + second)  + 86400];
        [_pedometer queryPedometerDataFromDate:nowDay toDate:nextDay withHandler:^(CMPedometerData * _Nullable pedometerData, NSError * _Nullable error) {
            if (error) {
                NSLog(@"error====%@",error);
            }else {
                NSLog(@"步数====%@",pedometerData.numberOfSteps);
                NSLog(@"距离====%@米",pedometerData.distance);
            }
        }];

六、蓝牙

以后更新

参考

http://blog.csdn.net/andy_jiangbin/article/details/9991335
http://www.jianshu.com/p/233be81b8ead
https://segmentfault.com/a/1190000000476207

上一篇 下一篇

猜你喜欢

热点阅读