iOS 傳感器

目錄
一、距離傳感器
二、加速計
三、磁力計、陀螺儀的使用和上述加速計的使用步驟類似
四、搖一搖
五、步數(shù)

一、距離傳感器

  • 監(jiān)聽方式:添加觀察者,監(jiān)聽通知

  • 通知名稱:UIDeviceProximityStateDidChangeNotification

  • 監(jiān)聽狀態(tài):觀察者的對應(yīng)回調(diào)方法中,判斷[UIDevice currentDevice].proximityState
    ?? 返回 NO:有物品靠近了
    ?? 返回 YES:有物品遠(yuǎn)離了

  • 注意:使用前要打開當(dāng)前設(shè)備距離傳感器的開關(guān)(默認(rèn)為:NO):

[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(@"有物品遠(yuǎn)離");
    }
}

二、加速計

  • 概述:
    檢測設(shè)備在X/Y/Z軸的受力情況
加速計.png
  • 備注:UIAccelerationUIAccelerometer在iOS 5.0中寂靜被棄用。由Core Motion framework取代

Core Moton 獲取數(shù)據(jù)的兩種方式:

  • push:實時采集所有數(shù)據(jù),采集頻率高;
  • pull:在有需要的時候才去采集數(shù)據(jù);
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. 設(shè)置采樣間隔
    self.mgr.accelerometerUpdateInterval = 1.0 / 30.0; // 1秒鐘采樣30次
    
    // 3. 開始采樣
    [self.mgr startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
        // 當(dāng)采樣到加速計信息時就會執(zhí)行
        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
  • 2.設(shè)置傳感器的采樣間隔:
    加速計
@property(assign, nonatomic) NSTimeInterval accelerometerUpdateInterval;

陀螺儀

@property(assign, nonatomic) NSTimeInterval gyroUpdateInterval;

磁力計

@property(assign, nonatomic) NSTimeInterval magnetometerUpdateInterval
  • 3.1 開始采樣的方法push
    加速計
- (void)startAccelerometerUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMAccelerometerHandler)handler;

陀螺儀

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

磁力計

- (void)startMagnetometerUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMMagnetometerHandler)handler;
  • 3.2 pull方式
    加速計
- (void)startAccelerometerUpdates;

陀螺儀

- (void)startGyroUpdates;

磁力計

- (void)startMagnetometerUpdates;
  • 4.1 獲取采樣的數(shù)據(jù) push
    在對應(yīng)的傳感器的開始采樣方法中的handler
  • 4.2 pull方式
    加速計
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子類中,需要實現(xiàn)canBecomeFirstResponder方法,并返回YES(默認(rèn)返回FALSE),
才可使becomeFirstResponder可返回YES,才可使其成為第一響應(yīng)者,即接受第一響應(yīng)者狀態(tài)。

一個響應(yīng)者只有當(dāng)當(dāng)前響應(yīng)者可以取消第一響應(yīng)者狀態(tài) (canResignFirstResponder) 并且新的響應(yīng)者可以成為第一響應(yīng)者時,才可以成為第一響應(yīng)者。
*/
-(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

五、步數(shù)

if (![CMPedometer isStepCountingAvailable]) {
      NSLog(@"計步器不可用");
      return;
  }
CMPedometer *stepCounter = [[CMPedometer alloc] init];
 [stepCounter startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData *pedometerData, NSError *error) {
      if (error) return;
      // 4.獲取采樣數(shù)據(jù),實時走
      NSLog(@"steps = %@", pedometerData.numberOfSteps);
  }];

統(tǒng)計今天走了多少步,多遠(yuǎn),垂直,室內(nèi)導(dǎo)航等
http://www.itdecent.cn/p/e5f332f9b27c
還可通過HealthKit框架獲取今日步數(shù), 參考以下鏈接
http://www.itdecent.cn/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(@"步數(shù)====%@",pedometerData.numberOfSteps);
                NSLog(@"距離====%@米",pedometerData.distance);
            }
        }];

六、藍(lán)牙

以后更新

參考

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

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

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

  • 猜猜運用以下哪個傳感器:點這里下載(下載了,記得點星星,謝謝!) 傳感器的...
    在逃科學(xué)家閱讀 2,471評論 0 1
  • 1 . iOS設(shè)備的傳感器簡介 (注釋 所有的調(diào)試設(shè)備必須是真機) 1.1 環(huán)境傳感器 Ambient Ligh...
    cj小牛閱讀 1,303評論 0 6
  • 一. 簡介 iOS設(shè)備內(nèi)置了一些傳感器,并提供了相關(guān)的API供調(diào)用,關(guān)于iOS傳感器的類型及作用等相關(guān)知識,可以查...
    YaoYaoX閱讀 10,335評論 1 13
  • 1.傳感器的定義:傳感器是一種感應(yīng)、檢測裝置 2.傳感器的作用:用于檢測、感應(yīng)設(shè)備的周邊信息;不用類型的傳感器,檢...
    archyly閱讀 1,769評論 0 3
  • 傳感器集錦 :指紋識別、運動傳感器、加速計、環(huán)境光感、距離傳感器、磁力計、陀螺儀 一、指紋識別 應(yīng)用:指紋解鎖、指...
    且行且珍惜_iOS閱讀 4,915評論 4 32

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