How to use torch light in iPhone app?
16,762
I have a torch button in my app which uses the following 3 methods.
- (void)initialiseTorch {
if (!session) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
session = [[AVCaptureSession alloc] init];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
[session addInput:input];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
[session startRunning];
[output release];
}
}
- (void)releaseTorch {
if (session) {
[session stopRunning];
[session release];
session = nil;
}
}
- (void) lightButtonPressed {
if (!session) {
[self initialiseTorch];
}
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[session beginConfiguration];
[device lockForConfiguration:nil];
if ([device torchMode] == AVCaptureTorchModeOn) {
[device setTorchMode:AVCaptureTorchModeOff];
} else {
[device setTorchMode:AVCaptureTorchModeOn];
}
[device unlockForConfiguration];
[session commitConfiguration];
}
The only difference I can see between our code is that you are also setting the Flash Mode. Also I configure my session, and then turn the torch on/off in a seperate beginConfiguration pass
Comments
-
Yuvaraj.M almost 2 years
I need to use iPhone Flash light in my app. But, while the user switch on the flash the camera does not take picture. How can i do this? Here i have attached my code. But, when i switch on the flash light, the camera takes picture.
AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil]; AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init]; AVCaptureSession *session = [[AVCaptureSession alloc] init]; [session beginConfiguration]; [device lockForConfiguration:nil]; [device setTorchMode:AVCaptureTorchModeOn]; [device setFlashMode:AVCaptureFlashModeOn]; [session addInput:flashInput]; [session addOutput:output]; [device unlockForConfiguration]; [output release]; [session commitConfiguration]; [session startRunning]; [self setTorchSession:session];
Where i am wrong in coding? Please help me. Thanks in advance.
-
Brad Larson over 12 yearspossible duplicate of Turn on torch/flash on iPhone 4
-