iOS中傳感器的基本使用

iOS中常見的傳感器

iOS中常見的傳感器

一.距離傳感器

  • 監聽方式:添加觀察者,監聽通知

  • 通知名稱:UIDeviceProximityStateDidChangeNotification

  • 監聽狀態:觀察者的對應回調方法中,判斷[UIDevice currentDevice].proximityState

    • 返回 NO : 有物品靠近了;
    • 返回 YES : 有物品遠離了
  • 注意:使用前要打開當前設備距離傳感器的開關(默認為:NO):

[UIDevice currentDevice].proximityMonitoringEnabled = YES;


- 示例程序:

  • (void)viewDidLoad
    {
    [super viewDidLoad];

    // [UIApplication sharedApplication].proximitySensingEnabled = YES;
    [UIDevice currentDevice].proximityMonitoringEnabled = YES;

    // 監聽有物品靠近還是離開
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
    }

  • (void)proximityStateDidChange
    {
    if ([UIDevice currentDevice].proximityState) {
    NSLog(@"有物品靠近");
    } else {
    NSLog(@"有物品離開");
    }
    }


### 二.加速計(UIAccelerometer)
- 概述:
檢測設備在`X/Y/Z軸`上的`受力`情況
![加速計](http://upload-images.jianshu.io/upload_images/590107-98de475675ae93b7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
- 監聽方式:設置`代理`

- 使用步驟:(iOS5之前)
   - 獲取加速計`單例`對象:

UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];


   - 設置加速計`代理`對象

accelerometer.delegate = self;


   - 設置`采樣間隔` : `updateInterval`

accelerometer.updateInterval = 0.3;


   - 實現代理相關方法,監聽加速計的數據
  • (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration;
      - `UIAcceleration `參數:
         ```
@interface UIAcceleration : NSObject {
  @private
    NSTimeInterval timestamp;
    UIAccelerationValue x, y, z;
}
  • 示例程序:
#import "ViewController.h"

@interface ViewController () <UIAccelerometerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.獲取單例對象
    UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
    
    // 2.設置代理
    accelerometer.delegate = self;
    
    // 3.設置采樣間隔
    accelerometer.updateInterval = 0.3;
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    NSLog(@"x:%f y:%f z:%f", acceleration.x, acceleration.y, acceleration.z);
}

@end
  • 備注:UIAccelerationUIAccelerometer在iOS 5.0中已經被棄用。由Core Motion framework取代。

  • 官方提示信息:

UIAcceleration and UIAccelerometer are deprecated as of iOS 5.0. These classes have been replaced by the Core Motion framework.

三 . Core Motion

  • Core Motion獲取數據的兩種方式:
    • push : 實時采集所有數據,采集頻率高;
    • pull : 在有需要的時候,才去采集數據;
Core Motion的使用步驟---push
  • 1.創建運動管理對象
CMMotionManager*mgr = [[CMMotionManageralloc]init];
  • 2.判斷加速器是否可用(最好判斷)
if(mgr.isAccelerometerAvailable){
    //加速計可用
}
  • 3.設置采樣間隔
mgr.accelerometerUpdateInterval= 1.0/30.0;// 1秒鐘采樣30次
  • 4.開始采樣(采樣到數據就會調用handler,handler會在queue中執行)
-(void)startAccelerometerUpdatesToQueue:(NSOperationQueue*)queue withHandler:(CMAccelerometerHandler)handler;
  • 示例程序:
#import "ViewController.h"

@interface ViewController () <UIAccelerometerDelegate>

/** 運動管理者 */
@property (nonatomic, strong) CMMotionManager *mgr; // 保證不死

@end

@implementation ViewController

#pragma mark - 懶加載
- (CMMotionManager *)mgr
{
    if (_mgr == nil) {
        _mgr = [[CMMotionManager alloc] init];
    }
    return _mgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    // 1.判斷加速計是否可用
    if (!self.mgr.isAccelerometerAvailable) {
        NSLog(@"加速計不可用");
        return;
    }
    
    // 2.設置采樣間隔
    self.mgr.accelerometerUpdateInterval = 0.3;
    
    // 3.開始采樣
    [self.mgr startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) { // 當采樣到加速計信息時就會執行
        if (error) return;
        
        // 4.獲取加速計信息
        CMAcceleration acceleration = accelerometerData.acceleration;
        NSLog(@"x:%f y:%f z:%f", acceleration.x, acceleration.y, acceleration.z);
    }];
}
@end
Core Motion的使用步驟---pull
  • 說明 : pull是在需要時獲取數據,我們此時以點擊了屏幕就獲取一次數據為例說明;

  • 1.創建運動管理對象

CMMotionManager*mgr = [[CMMotionManageralloc]init];
  • 2.判斷加速器是否可用(最好判斷)
if(mgr.isAccelerometerAvailable){
    //加速計可用
}
  • 3.開始采樣
-(void)startAccelerometerUpdates;
  • 4.在需要時獲取數據
CMAcceleration acc = mgr.accelerometerData.acceleration;
NSLog(@"%f,%f, %f", acc.x,acc.y,acc.z);
  • 示例程序:
#import "ViewController.h"

@interface ViewController () <UIAccelerometerDelegate>

/** 運動管理者 */
@property (nonatomic, strong) CMMotionManager *mgr; // 保證不死

@end

@implementation ViewController

#pragma mark - 懶加載
- (CMMotionManager *)mgr
{
    if (_mgr == nil) {
        _mgr = [[CMMotionManager alloc] init];
    }
    return _mgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    // 1.判斷加速計是否可用
    if (!self.mgr.isAccelerometerAvailable) {
        NSLog(@"加速計不可用");
        return;
    }
    
    // 2.開始采樣
    [self.mgr startAccelerometerUpdates];
}
@end

    // 3.數據采樣(以點擊了屏幕為例說明)
- (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);
}

四.磁力計/陀螺儀的使用和上述加速計的使用步驟類似

不同點:

  • 1.判斷傳感器是否可用:

    • 加速計:
@property(readonly, nonatomic, getter=isAccelerometerAvailable) BOOL accelerometerAvailable;
  • 陀螺儀:
@property(readonly, nonatomic, getter=isGyroAvailable) BOOL gyroAvailable;
  • 磁力計:
@property(readonly, nonatomic, getter=isMagnetometerAvailable) BOOL magnetometerAvailable
  • 2.設置傳感器的采樣間隔:

    • 1.加速計:
@property(assign, nonatomic) NSTimeInterval accelerometerUpdateInterval;
  • 2.陀螺儀:
@property(assign, nonatomic) NSTimeInterval gyroUpdateInterval;
  • 3.磁力計:
@property(assign, nonatomic) NSTimeInterval magnetometerUpdateInterval
  • 3.1.開始采樣的方法--push:

    • 1.加速計:
 - (void)startAccelerometerUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMAccelerometerHandler)handler;
  • 2.陀螺儀:
 - (void)startGyroUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMGyroHandler)handler;
  • 3.磁力計:
 - (void)startMagnetometerUpdatesToQueue:(NSOperationQueue *)queue withHandler:(CMMagnetometerHandler)handler;
  • 3.2.開發采樣的方法--pull

    • 1.加速計:
 - (void)startAccelerometerUpdates;
  • 2.陀螺儀:
 - (void)startGyroUpdates;
  • 3.磁力計:
 - (void)startMagnetometerUpdates;
  • 4.1獲取采樣數據--push

    • 在對應的傳感器的開始采樣方法中的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);

五.沒事你就,搖一搖

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

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

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

六. 沒事走兩步(計步器)

  • 1.判斷計步器是否可用
    if (![CMPedometer isStepCountingAvailable]) {
        NSLog(@"計步器不可用");
        return;
    }
  • 2.創建計步器對象
CMPedometer *stepCounter = [[CMPedometer alloc] init];
  • 3.開始記步,并獲取采樣數據
    [stepCounter startPedometerUpdatesFromDate:[NSDate date] withHandler:^(CMPedometerData *pedometerData, NSError *error) {
        if (error) return;
        // 4.獲取采樣數據
        NSLog(@"steps = %@", pedometerData.numberOfSteps);
    }];

七.藍牙

  • 簡述:
    iOS中提供了4個框架用于實現藍牙連接:
    • 1.GameKit.framework

      • 只能用于iOS設備之間的連接,多用于游戲(比如五子棋對戰),可以在游戲中增加對等連接,又稱對端連接點對點連接 Peer To Peer,從iOS7開始過期
    • 2.MultipeerConnectivity.framework

      • 只能用于iOS設備之間的連接,從iOS7開始引入
    • 3.ExternalAccessory.framework

      • 可用于第三方藍牙設備交互,但是藍牙設備必須經過蘋果MFi認證(國內較少)
    • 4.CoreBluetooth.framework(時下熱門)

      • 可用于第三方藍牙設備交互,必須要支持藍牙4.0;
      • 硬件至少是4s,系統至少是iOS6;
      • 藍牙4.0以低功耗著稱,一般也叫BLE(BluetoothLowEnergy)
      • 目前應用比較多的案例:運動手壞、嵌入式設備、智能家居
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容