I see several problems with this code. First you use
name:@"UIDeviceProximityStateDidChangeNotification"
instead
name:UIDeviceProximityStateDidChangeNotification
Both work, but using an empty version you will get a compiler error if you create a typo. (You want to get a compiler error with typos, this will prevent silent errors).
The next thing you do not actually verify is that the proximity sensor is available before adding a notification. Your code:
BOOL state = device.proximityState
But it just checks if the device is close to the face of the user. You really want to set proximityEnabled
to YES
, and then verify that it is actually installed. This is a bit controversial.
UIDevice *device = [UIDevice currentDevice]; [device setProximityMonitoringEnabled:YES]; if ([device isProximityMonitoringEnabled]) {
Here is an example of the complete code:
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; UIDevice *device = [UIDevice currentDevice]; // Register for proximity notifications [device setProximityMonitoringEnabled:YES]; if ([device isProximityMonitoringEnabled]) { [notificationCenter addObserver:self selector:@selector(proximityChanged:) name:UIDeviceProximityStateDidChangeNotification object:device]; } else { NSLog(@"No Proximity Sensor"); }
source share