启用AR Camera时,iPhone X手电筒关闭

时间:2018-05-23 14:39:26

标签: ios objective-c arkit iphone-x flashlight

我正在构建一个需要手电筒打开手电筒模式的AR应用程序。打开手电筒模式,然后启用AR场景在我的iPhone 8上工作正常,但在iPhone X上,手电筒打开然后再关闭。有没有办法解决这个问题,或者我需要做些什么才能使iPhone X正常工作?

- (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];
        }
    }
}

然后是:

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;

更具体地说,这条线关闭了手电筒:

self.sceneView = [[ARSCNView alloc] initWithFrame:self.view.frame];

1 个答案:

答案 0 :(得分:0)

我希望用Swift编写的逻辑稍有不同(由于guard语句)的代码可以在您的iPhone X上使用,但是老实说,我还没有尝试过。

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)

希望这会有所帮助。