距离传感器集成在UIDevice类中,Apple电话APP自动开启距离传感器,但是开发者自己的APP需要手动开启距离传感器
开启方式很简单,只需一行代码:
// 开启距离传感器
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
使用场景:
通常是在语音,网络会话时,当手机贴近脸部时,关闭屏幕,或执行某些操作
监听距离变化(通知),使用UIDevice的proximityState属性:
@property(nonatomic,readonly) BOOL proximityState
// 监听距离的变化(通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
- (void)proximityStateDidChange{
if ([UIDevice currentDevice].proximityState) {
// 近距离
NSLog(@"滚远点,贴脸上了");
} else {
// 远距离
NSLog(@"亲爱的,靠近点");
}
}
实例代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 开启距离传感器
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
// 监听距离的变化(通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateDidChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
}
- (void)proximityStateDidChange{
if ([UIDevice currentDevice].proximityState) {
// 近距离
NSLog(@"滚远点,贴脸上了");
} else {
// 远距离
NSLog(@"亲爱的,靠近点");
}
}
@end
还可以通过距离监听,来判断是否禁止自动锁屏,需要使用UIApplication的idleTimerDisabled属性
@property(nonatomic,getter=isIdleTimerDisabled) BOOL idleTimerDisabled;
演示代码:
NSString *sessionType = @"语音";
if ([sessionType isEqualToString:@"语音"]) { //语音
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
} else { //视频
[UIDevice currentDevice].proximityMonitoringEnabled = NO;
//禁用自动锁屏
[UIApplication sharedApplication].idleTimerDisabled = YES;
}