(九十一)距离传感器的使用

Posted ljbguanli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(九十一)距离传感器的使用相关的知识,希望对你有一定的参考价值。

iPhone上的距离传感器通过UIDevice开启,开启后系统以Notification的方式通知。

①开启距离传感器。监听通知:

- (void)viewDidLoad {
    [super viewDidLoad];

    // 开启传感器在ios3之后通过UIDevice的currentDevice的proximityMonitoringEnabled设置
    [UIDevice currentDevice].proximityMonitoringEnabled = YES;
    
    // 监听到物体靠近时,系统会发出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximityStateChange:) name:UIDeviceProximityStateDidChangeNotification object:nil];
    
}

②实现通知方法:当物体靠近距离传感器时,手机会自己主动锁屏,而且proximityState为YES,否则为NO。

- (void)proximityStateChange:(NSNotification *)nof{
    
    NSLog(@"%d",[UIDevice currentDevice].proximityState);
    if ([UIDevice currentDevice].proximityState) {
        NSLog(@"靠近");
    }else{
        NSLog(@"离开");
    }
    
}

③dealloc时要移除通知:

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


以上是关于(九十一)距离传感器的使用的主要内容,如果未能解决你的问题,请参考以下文章