使用使用近距離傳感器
UIDevice 中有兩個近距離傳感器的屬性:proximityMonitoringEnabled 和 proximityState。這兩個屬性都是 iOS 3.0 及以上才支持的。
要確定近距離傳感器是否可用,可以嘗試啟用它,即 proximityMonitoringEnabled = YES,如果設(shè)置的屬性值仍然為NO,說明傳感器不可用。
proximityState 屬性
傳感器已啟動前提條件下,如果用戶接近近距離傳感器,此時屬性值為YES,并且屏幕已關(guān)閉(非休眠)。
Notification
UIDeviceProximityStateDidChangeNotification,當(dāng)近距離傳感器狀態(tài)改變時發(fā)生。
代碼實現(xiàn):
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 1.開啟距離傳感器
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
// 2.發(fā)送通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityState) name:UIDeviceProximityStateDidChangeNotification object:nil];
}
// 3.近距離傳感器狀態(tài)改變
- (void)proximityState
{
if ([UIDevice currentDevice].proximityState) {
NSLog(@"有物體靠近");
}else{
NSLog(@"有物體離開");
}
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
使用場景:
可以通過近距離傳感器計算做俯臥撐次數(shù)

俯臥撐.png