質問

I am using this below code for switch on the Torch light in iphone app. It working fine. The issue is, when we press the button the torch mode will be changed to 'On' but, the torch light only appear when the user entering into the Camera screen. I want to switch on the torch light without using the Camera screen. Can anyone please guide me? Please suggest me where i am wrong. Here my code,

captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (captureDevice.torchMode == AVCaptureTorchModeOff)  
    {
        AVCaptureSession *session = [[AVCaptureSession alloc] init];
        [session beginConfiguration];

        [captureDevice lockForConfiguration:nil];
        [captureDevice setTorchMode:AVCaptureTorchModeOn];
        [captureDevice unlockForConfiguration];

        [session commitConfiguration];
        [session startRunning];

        [self setTorchSession:session];
        [session release];
    }
    else 
    {
        [torchSession stopRunning];
        [captureDevice setTorchMode:AVCaptureTorchModeOff];
    }

Is this correct code for Torch Light in iPhone? Please help me. Thanks in advance.

役に立ちましたか?

解決

This code works for me

- (void) internal_setFlashOn: (BOOL) turnOn {
  AVCaptureDevice *theDevice = self.captureDevice;

  if ([theDevice hasTorch]) {
    [theDevice lockForConfiguration: nil];
    AVCaptureTorchMode currentMode = [theDevice torchMode];
    BOOL isAlreadyTurnedOn = (AVCaptureTorchModeOn == currentMode);
    if (isAlreadyTurnedOn != turnOn) {
      [theDevice setTorchMode: turnOn? AVCaptureTorchModeOn: AVCaptureTorchModeOff];
    }

    [theDevice unlockForConfiguration];
  }
}

- (AVCaptureDevice *) captureDevice {
  if (nil == internal_captureDevice) {
    internal_captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    [internal_captureDevice retain];
  }
  return internal_captureDevice;
}

This works on iPhone4 and above.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top