detecting if iPhone is in a dark room

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.

Leave a Comment