【iOS】傳感器

距離傳感器

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1.開啟距離傳感器(注意: 默認(rèn)情況距離傳感器是關(guān)閉的)
    // 這個(gè)方法是廢棄的
    // [UIApplication sharedApplication].proximitySensingEnabled = YES;
    
    // 只要開啟之后, 就開始實(shí)時(shí)監(jiān)聽
    [UIDevice currentDevice].proximityMonitoringEnabled = YES;
    
    // 2.當(dāng)監(jiān)聽到有物體靠近設(shè)備時(shí)系統(tǒng)會發(fā)出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange:) name:UIDeviceProximityStateDidChangeNotification object:nil];
}


// 當(dāng)監(jiān)聽到有物體靠近設(shè)備時(shí)調(diào)用
-(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");
}

// 搖一搖結(jié)束(需要在這里處理結(jié)束后的代碼)
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    // 不是搖一搖運(yùn)動事件
    if (motion != UIEventSubtypeMotionShake) return;
    
    NSLog(@"motionEnded");
}

// 搖一搖取消(被中斷,比如突然來電)
-(void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionCancelled");
}

計(jì)步器

// 導(dǎo)入頭文件
#import <CoreMotion/CoreMotion.h>

/* 計(jì)步器對象 */
@property (nonatomic, strong) CMStepCounter * counter;
@property (nonatomic, weak) UILabel * stepLabel;

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

    // 2.開始計(jì)步 
    [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是一個(gè)專門處理Motion的框架,其中包含了兩個(gè)部分 加速度計(jì)和陀螺儀,在iOS4之前加速度計(jì)是由 UIAccelerometer 類來負(fù)責(zé)采集數(shù)據(jù),現(xiàn)在一般都是用CoreMotion來處理加速度過程,不過由于UIAccelerometer比較簡單,同樣有人在使用。加速計(jì)由三個(gè)坐標(biāo)軸決定,用戶最常見的操作設(shè)備的動作移動,晃動手機(jī)(搖一搖),傾斜手機(jī)都可以被設(shè)備檢測到,加速計(jì)可以檢測到線性的變化,陀螺儀可以更好的檢測到偏轉(zhuǎn)的動作,可以根據(jù)用戶的動作做出相應(yīng)的動作。

  • CoreMotion在處理加速計(jì)數(shù)據(jù)和陀螺儀數(shù)據(jù)的時(shí)是一個(gè)非常重要的框架,框架本身集成了很多算法獲取原生的數(shù)據(jù),而且能很好的展現(xiàn)出來,CoreMotionUIKit不同,連接的是UIEvent而不是事件響應(yīng)鏈。CoreMotion相對于接收數(shù)據(jù)只是更簡單的分發(fā)motion事件。

  • CMMotionManager 類能夠使用到設(shè)備的所有移動數(shù)據(jù)(motion data),Core Motion框架提供了兩種對motion數(shù)據(jù)的操作方式:

  • pull方式:能夠以CoreMotionManager的只讀方式獲取當(dāng)前任何傳感器狀態(tài)或是組合數(shù)據(jù)

  • push方式:是以塊或者閉包的形式收集到想要得到的數(shù)據(jù)并且在特定周期內(nèi)得到實(shí)時(shí)的更新

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

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

@implementation ViewController

-(void)viewDidLoad 
{
    [super viewDidLoad];
    
    // 1.創(chuàng)建coreMotion管理者
    self.mgr = [[CMMotionManager alloc] init];
    
    // 2.判斷加速計(jì)是否可用
    if (self.mgr.isAccelerometerAvailable) 
    {
        // 3.開始采樣
        [self.mgr setAccelerometerUpdateInterval:1 / 30.0];  // 設(shè)置加速計(jì)采樣頻率 
       
        [self.mgr startAccelerometerUpdates];  // pull
    }
    else
    {
         NSLog(@"加速計(jì)不可用");
    }
}

-(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.創(chuàng)建coreMotion管理者
    self.mgr = [[CMMotionManager alloc] init];
    
    // 2.判斷加速計(jì)是否可用
    if (self.mgr.isAccelerometerAvailable) 
    {
        /**
          * isAccelerometerActive 是否正在采集
          * accelerometerData 采集到得數(shù)據(jù)
          * startAccelerometerUpdates  - pull
          * startAccelerometerUpdatesToQueue  - push
          * stopAccelerometerUpdates 停止采集
          * accelerometerUpdateInterval 采樣頻率
          */
        
        // 3.設(shè)置采樣頻率
        self.mgr.accelerometerUpdateInterval = 1 / 30.0;
        
        // 4.開始采樣
        [self.mgr startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * accelerometerData, NSError * error) {
            
            // 這個(gè)block是采集到數(shù)據(jù)時(shí)就會調(diào)用
            if (error) return ;
            
            CMAcceleration acceleration = accelerometerData.acceleration;
            
            NSLog(@"x = %f y = %f z = %f", acceleration.x, acceleration.y , acceleration.z);
        }];
    }
    else
    {
        NSLog(@"加速計(jì)不可用");
    }
}

#pragma mark - 記得要設(shè)置懶加載
-(CMMotionManager *)mgr
{
    if (_mgr == nil) 
    { 
        _mgr = [[CMMotionManager alloc] init]; 
    } 
    return _mgr;
}

@end
  • 陀螺儀其實(shí)和加速計(jì)沒有區(qū)別

  • 陀螺儀更新數(shù)據(jù)也有兩種方式:

  • 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.設(shè)置采樣間隔
    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);
    }];
}

參考文獻(xiàn)
OC:傳感器
iOS開發(fā)-CoreMotion框架

歡迎關(guān)注我的微信公共號:iapp666666
GitHub:點(diǎn)此前往

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容