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];
}- (void)proximityStateChange:(NSNotification *)nof{
NSLog(@"%d",[UIDevice currentDevice].proximityState);
if ([UIDevice currentDevice].proximityState) {
NSLog(@"靠近");
}else{
NSLog(@"离开");
}
}- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}原文:http://www.cnblogs.com/ljbguanli/p/7100444.html