4

I am building an AR app that needs the flashlight to be turned on torch mode. Turning on torch mode and then enabling the AR scene works fine on my iPhone 8, but on the iPhone X, it the flashlight turns on and then off again. Is there some way around this, or something specific I have to do for the iPhone X to work?

- (void)turnTorchOn:(bool) on {
    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]){

            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
            }
            [device unlockForConfiguration];
        }
    }
}

And then later:

self.arConfig = [ARWorldTrackingConfiguration new];
self.arConfig.planeDetection = ARPlaneDetectionHorizontal;
self.sceneView = [[ARSCNView alloc] initWithFrame:self.view.frame];
[self.view addSubview:self.sceneView];

SCNScene *scene = [SCNScene new];
self.sceneView.scene = scene;
self.sceneView.autoenablesDefaultLighting = YES;
self.sceneView.delegate = self;
self.sceneView.session.delegate = self;

More specifically, this line turns off the flashlight:

self.sceneView = [[ARSCNView alloc] initWithFrame:self.view.frame];
evenodd
  • 2,026
  • 4
  • 26
  • 38
  • My guess would be that ARKit configuring the capture session/device interferes with what you've set. Have you tried turning on the torch after starting the AR session instead of before? – rickster May 23 '18 at 18:16
  • @rickster yeah I've tried switching the order and it also fails. Strange though that only the iPhone X has the issue. Any other ideas for me to try? – evenodd May 23 '18 at 18:28
  • Since this is only happening on the iPhone X, I would open a radar with Apple. – wottle Jun 12 '18 at 14:36

1 Answers1

0

I hope this code written in Swift with a slightly different logic (due to guard statement) may work for your iPhone X but, honestly saying, I haven't tried it yet.

func toggleTorch(on: Bool) {

    guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { 
        return 
    }
    if device.hasTorch {
        do {
            try device.lockForConfiguration()

            if on == true {
                device.torchMode = .on
            } else {
                device.torchMode = .off
            }

            device.unlockForConfiguration()

        } catch {
            print("Error. Torch couldn't be used")
        }
    } else {
        print("Torch isn't available")
    }
}

// CALL IT:

// toggleTorch(on: true)
// toggleTorch(on: false)

Hope this helps.

Andy Jazz
  • 49,178
  • 17
  • 136
  • 220