傳感器.png
- 距離傳感器
- (void)viewDidLoad {
[super viewDidLoad];
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
// 監(jiān)聽有物品靠近還是離開
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
}
- (void)proximityStateDidChange {
if ([UIDevice currentDevice].proximityState) {
NSLog(@"有物品靠近");
} else {
NSLog(@"有物品離開");
}
}
- 加速器
//push方式
// 創(chuàng)建運(yùn)動(dòng)管理者對(duì)象
self.manager = [[CMMotionManager alloc] init];
// 判斷加速計(jì)是否可用
if (!self.manager.isAccelerometerAvailable) {
NSLog(@"加速計(jì)不可用");
return;
}
// 設(shè)置采樣間隔
self.manager.accelerometerUpdateInterval = 0.3;
// 開始采樣
[self.manager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
// 當(dāng)采樣到加速計(jì)信息就會(huì)執(zhí)行
if (error) return;
// 獲取加速計(jì)信息
CMAcceleration acceleration = accelerometerData.acceleration;
NSLog(@"x:%f, y:%f ,z:%f", acceleration.x, acceleration.y, acceleration.z);
}];
- 陀螺儀
// 判斷陀螺儀是否可用
if (![self.manager isGyroAvailable]) {
NSLog(@"手機(jī)該換了");
return;
}
// 設(shè)置采樣間隔
self.manager.gyroUpdateInterval = 0.3;
// 開始采樣
[self.manager startGyroUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMGyroData * _Nullable gyroData, NSError * _Nullable error) {
if (error) return ;
CMRotationRate rate = gyroData.rotationRate;
NSLog(@"x:%f, y:%f, z:%f", rate.x, rate.y, rate.z);
}];