0

I've tried to write my own module to detect is torch turned on/off.

According to documentation I've tried to run KVC as below

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == torchActiveObservationContext) {
        AVCaptureDevice *thisDevice = (AVCaptureDevice*)object;
        [self sendEventWithName:@"TorchEvent" body:@{@"isTorchActive": thisDevice.isTorchActive ? @"ACTIVE" : @"INACTIVE"}];
        NSLog( @"Current torch level: %f", thisDevice.torchLevel);

    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        NSLog( @"ABCDEF");
    }
}

-(id) init {
    if (self = [super init]) {
        NSLog( @"Start Initialization");
        AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

        [videoDevice addObserver:self forKeyPath:@"isTorchActive" options:NSKeyValueObservingOptionNew context:torchActiveObservationContext];
        NSLog( @"End Initialization");
        // whatever other initialization code ...
    }
    return self;
}

But I noticed that any change is recorded if i try to turn on the torch in Control Panel. So i tried to do it much easier and check the current torch state manually. I created simple method:

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(isTorchActive)
{
    AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCapturePhotoSettings *photosettings = [AVCapturePhotoSettings photoSettings];
            
    NSLog( videoDevice.isTorchActive ? @"on" : @"off");
    NSLog( @"Level : %f", videoDevice.torchLevel);
    return videoDevice.isTorchActive ? @"on" : @"off";
}

But it returns "off" all the time, even if torch is initially flashed. Torch level is 0.0.

What am I doing wrong?

Jaroslaw K.
  • 5,224
  • 2
  • 39
  • 65

1 Answers1

0

Replace videoDevice.isTorchActive with videoDevice.torchMode == AVCaptureTorchModeOn If torch was previously activated from Control Center, you can get AVCaptureTorchModeOff, when running this code first time.

Neil Galiaskarov
  • 5,015
  • 2
  • 27
  • 46