美文网首页iOS
【iOS】传感器

【iOS】传感器

作者: 雨声不吃鱼 | 来源:发表于2016-11-11 11:15 被阅读0次

距离传感器

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1.开启距离传感器(注意: 默认情况距离传感器是关闭的)
    // 这个方法是废弃的
    // [UIApplication sharedApplication].proximitySensingEnabled = YES;
    
    // 只要开启之后, 就开始实时监听
    [UIDevice currentDevice].proximityMonitoringEnabled = YES;
    
    // 2.当监听到有物体靠近设备时系统会发出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange:) name:UIDeviceProximityStateDidChangeNotification object:nil];
}


// 当监听到有物体靠近设备时调用
-(void)proximityStateDidChange:(NSNotification *)note
{
   if([UIDevice currentDevice].proximityState)
   {
       NSLog(@"有物体靠近");
   }
   else
   {
       NSLog(@"物体离开");
   }
}

// 移除通知
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

摇一摇

// 开始摇一摇
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionBegan");
}

// 摇一摇结束(需要在这里处理结束后的代码)
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    // 不是摇一摇运动事件
    if (motion != UIEventSubtypeMotionShake) return;
    
    NSLog(@"motionEnded");
}

// 摇一摇取消(被中断,比如突然来电)
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionCancelled");
}

计步器

// 导入头文件
#import <CoreMotion/CoreMotion.h>

/* 计步器对象 */
@property (nonatomic, strong) CMStepCounter * counter;
@property (nonatomic, weak) UILabel * stepLabel;

-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    
    // 1.判断计步器是否可用 
    if (![CMStepCounter isStepCountingAvailable]) 
    { 
        NSLog(@"计步器不可用"); 
        return; 
    } 

    // 2.开始计步 
    [self.counter startStepCountingUpdatesToQueue:[NSOperationQueue mainQueue] updateOn:5 withHandler:^(NSInteger numberOfSteps, NSDate * timestamp, NSError * error) { 
        if (error) return; 
        self.stepLabel.text = [NSString stringWithFormat:@"您一共走了%ld步", numberOfSteps]; 
    }];
}

#pragma mark - 懒加载代码
-(CMStepCounter *)counter
{ 
    if (_counter == nil) 
    { 
        _counter = [[CMStepCounter alloc] init]; 
    } 
    return _counter;
}

CoreMotion框架

  • CoreMotion是一个专门处理Motion的框架,其中包含了两个部分 加速度计和陀螺仪,在iOS4之前加速度计是由 UIAccelerometer 类来负责采集数据,现在一般都是用CoreMotion来处理加速度过程,不过由于UIAccelerometer比较简单,同样有人在使用。加速计由三个坐标轴决定,用户最常见的操作设备的动作移动,晃动手机(摇一摇),倾斜手机都可以被设备检测到,加速计可以检测到线性的变化,陀螺仪可以更好的检测到偏转的动作,可以根据用户的动作做出相应的动作。

  • CoreMotion在处理加速计数据和陀螺仪数据的时是一个非常重要的框架,框架本身集成了很多算法获取原生的数据,而且能很好的展现出来,CoreMotionUIKit不同,连接的是UIEvent而不是事件响应链。CoreMotion相对于接收数据只是更简单的分发motion事件。

  • CMMotionManager 类能够使用到设备的所有移动数据(motion data)Core Motion框架提供了两种对motion数据的操作方式:

  • pull方式:能够以CoreMotionManager的只读方式获取当前任何传感器状态或是组合数据

  • push方式:是以块或者闭包的形式收集到想要得到的数据并且在特定周期内得到实时的更新

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

@interface ViewController ()
@property (nonatomic, strong) CMMotionManager * mgr;
@end

@implementation ViewController

-(void)viewDidLoad 
{
    [super viewDidLoad];
    
    // 1.创建coreMotion管理者
    self.mgr = [[CMMotionManager alloc] init];
    
    // 2.判断加速计是否可用
    if (self.mgr.isAccelerometerAvailable) 
    {
        // 3.开始采样
        [self.mgr setAccelerometerUpdateInterval:1 / 30.0];  // 设置加速计采样频率 
       
        [self.mgr startAccelerometerUpdates];  // pull
    }
    else
    {
         NSLog(@"加速计不可用");
    }
}

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

-(void)push
{
    // 1.创建coreMotion管理者
    self.mgr = [[CMMotionManager alloc] init];
    
    // 2.判断加速计是否可用
    if (self.mgr.isAccelerometerAvailable) 
    {
        /**
          * isAccelerometerActive 是否正在采集
          * accelerometerData 采集到得数据
          * startAccelerometerUpdates  - pull
          * startAccelerometerUpdatesToQueue  - push
          * stopAccelerometerUpdates 停止采集
          * accelerometerUpdateInterval 采样频率
          */
        
        // 3.设置采样频率
        self.mgr.accelerometerUpdateInterval = 1 / 30.0;
        
        // 4.开始采样
        [self.mgr startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * accelerometerData, NSError * error) {
            
            // 这个block是采集到数据时就会调用
            if (error) return ;
            
            CMAcceleration acceleration = accelerometerData.acceleration;
            
            NSLog(@"x = %f y = %f z = %f", acceleration.x, acceleration.y , acceleration.z);
        }];
    }
    else
    {
        NSLog(@"加速计不可用");
    }
}

#pragma mark - 记得要设置懒加载
-(CMMotionManager *)mgr
{
    if (_mgr == nil) 
    { 
        _mgr = [[CMMotionManager alloc] init]; 
    } 
    return _mgr;
}

@end
  • 陀螺仪其实和加速计没有区别

  • 陀螺仪更新数据也有两种方式:

  • pull 方式 ( startGyroUpdates )

  • push 方式 ( startGyroUpdatesToQueue )

#pragma mark - 获取陀螺仪信息
// pull
-(void)pullGyro
{
    // 1.判断陀螺仪是否可用
    if (![self.mgr isGyroAvailable])
    {
        NSLog(@"陀螺仪不可用");
        return;
    }
    
    // 2.开始采样
    [self.mgr startGyroUpdates];
}

// push
-(void)pushGyro
{
    // 1.判断陀螺仪是否可用
    if (![self.mgr isGyroAvailable])
    {
        NSLog(@"陀螺仪不可用");
        return;
    }
    
    // 2.设置采样间隔
    self.mgr.gyroUpdateInterval = 0.3;
    
    // 3.开始采样
    [self.mgr startGyroUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMGyroData *gyroData, NSError *error) {
        
        if (error) return;
        
        CMRotationRate rate = gyroData.rotationRate;
        
        NSLog(@"x = %f y = %f z = %f", rate.x, rate.y, rate.z);
    }];
}

参考文献
OC:传感器
iOS开发-CoreMotion框架

欢迎关注我的微信公共号:iapp666666
GitHub:点此前往

相关文章

网友评论

    本文标题:【iOS】传感器

    本文链接:https://www.haomeiwen.com/subject/mycfpttx.html