detecting if iPhone is in a dark room

Is there a way to use the iPhone proximity sensor to detect whether the phone is in a room with no light?

This question seems to imply that this is not possible...Does iPhone allow Light sensors as input?


Solution 1:

Here's a much simpler way of using the camera to find out how bright a scene is. (Obviously, it only reads the data that can be "seen" in the camera's field of view, so it's not a true ambient light sensor...)

Using the AVFoundation framework, set up a video input and then, using the ImageIO framework, read the metadata that's coming in with each frame of the video feed (you can ignore the actual video data):

#import <ImageIO/ImageIO.h>

- (void)captureOutput:(AVCaptureOutput *)captureOutput
      didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
             fromConnection:(AVCaptureConnection *)connection
{
  CFDictionaryRef metadataDict = CMCopyDictionaryOfAttachments(NULL, 
    sampleBuffer, kCMAttachmentMode_ShouldPropagate);
  NSDictionary *metadata = [[NSMutableDictionary alloc] 
    initWithDictionary:(__bridge NSDictionary*)metadataDict];
  CFRelease(metadataDict);
  NSDictionary *exifMetadata = [[metadata 
    objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy];
  float brightnessValue = [[exifMetadata 
    objectForKey:(NSString *)kCGImagePropertyExifBrightnessValue] floatValue];
}

You now have the Brightness Value for the scene updated (typically—you can configure this) 15-30 times per second. Lower numbers are darker.

Solution 2:

Proximity sensor is not what you should be looking for. Ambient light sensor it is. Apparently that API is undocumented or not available at all for developers. An alternative way of detecting if iPhone is in a dark room would be using the camera and obtaining the luminosity . Here's a good guide on how to do that,

https://www.transpire.com/insights/blog/obtaining-luminosity-ios-camera/