版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/potato512/article/details/83014339
设备距离传感器功能的使用,首先需要开启距离传感器功能,其次添加距离监听。
具体实现如下:
1、开启及监听
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateProximity) name:UIDeviceProximityStateDidChangeNotification object:nil];
2、实现监听方法
- (void)updateProximity
{
if ([UIDevice currentDevice].proximityState) {
self.label.text = @"有物体在靠近设备";
// 振动效果 需要#import <AudioToolbox/AudioToolbox.h>
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} else {
self.label.text = @"物体远离了设备";
// 振动效果 需要#import <AudioToolbox/AudioToolbox.h>
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
}
3、关闭及移除监听
[UIDevice currentDevice].proximityMonitoringEnabled = NO;
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceProximityStateDidChangeNotification object:nil];
```