0

I am using AVFoundation in iOS to manipulate the torch on an iPhone 6. I need to know the current torch level.

I've read in AppleDevLib that it's possible to observe the current torch level using KVO, but I've failed to implement that.

Can you put down some sample that detect change of torch level and then changes a variable (like label on screen etc.) please? It will help me a lot.

Miki Stuchlej
  • 147
  • 2
  • 7

1 Answers1

0

It took a while for me to figure out how to do this but I believe this KVO code will work for you. I haven't tested this code out thoroughly but I did get it basically working in an app:

static void * const torchLevelObservationContext = (void*)&torchLevelObservationContext;

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == torchLevelObservationContext) {
        AVCaptureDevice *thisDevice = (AVCaptureDevice*)object;
        NSLog( @"Current torch level: %f", thisDevice.torchLevel);
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

-(id) init {
    if (self = [super init]) {
        AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

        [videoDevice addObserver:self forKeyPath:@"torchLevel" options:NSKeyValueObservingOptionNew context:torchLevelObservationContext];

        // whatever other initialization code ...
    }
    return self;
}

Caveat: the main reason I was trying to use this code is to determine the current state of the torch that is turned on via the control center so I could leave it on when using the AVCaptureDevice and the torch is turned off for some reason once the capture starts. But no matter what I tried (torchActive, torchMode, torchLevel), I was unable to determine the state. This code only seems to work after it has taken control of the AVCaptureDevice and is using it an AVCaptureSession. If anyone knows how to get the current state of the flashlight or torch that is turned on from the control center, that is what I am trying to do.

Adam Freeman
  • 1,271
  • 12
  • 20