Dimming the LED for iPhone 5 flashlight app in Xcode - iphone

I am looking to dim the flashlight's LED with a slider option. I know Apple supports this for iOS 6 however, I am not really sure what code to use. Here is the code I have currently in the .m file.
-(IBAction)torchOn:(id)sender;
{
onButton.hidden = YES;
offButton.hidden = NO;
onView.hidden = NO;
offView.hidden = YES;
AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if([flashLight isTorchAvailable] && [flashLight isTorchModeSupported:AVCaptureTorchModeOn])
{
BOOL success = [flashLight lockForConfiguration:nil];
if(success)
{
[flashLight setTorchMode:AVCaptureTorchModeOn];
[flashLight unlockForConfiguration];
}
}
}
-(IBAction)torchOff:(id)sender;
{
onButton.hidden = NO;
offButton.hidden = YES;
onView.hidden = YES;
offView.hidden = NO;
AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if([flashLight isTorchAvailable] && [flashLight isTorchModeSupported:AVCaptureTorchModeOn])
{
BOOL success = [flashLight lockForConfiguration:nil];
if(success)
{
[flashLight setTorchMode:AVCaptureTorchModeOff];
[flashLight unlockForConfiguration];
}
}
}

- (BOOL)setTorchModeOnWithLevel:(float)torchLevel error:(NSError **)outError
Does what you want. However, from what I can see, it only updates in certain intervals (~0.2).
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
[device setTorchModeOnWithLevel:slider.value error:NULL];
[device unlockForConfiguration];
Edit - Full Example:
Here is a UISlider. You need to add an IBAction outlet to your slider or programmatically add a target (like I do):
UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(20.0f, 20.0f, 280.0f, 40.0f)];
slider.maximumValue = 1.0f;
slider.minimumValue = 0.0f;
[slider setContinuous:YES];
[slider addTarget:self action:#selector(sliderDidChange:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:slider];
Then, in response to the slider changing:
- (void)sliderDidChange:(UISlider *)slider
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
[device setTorchModeOnWithLevel:slider.value error:NULL];
[device unlockForConfiguration];
}

If there are two sliders it's because the slider is set in the m. file you have to delete the [self.view addSubview:slider]; part of the code.

Related

Blinking flash light at the time of taking image from Camera

I am using AVCapture frame work to set blinking flash light at the time of taking photo from camera. In this method I am getting flash light blinking effect for a few seconds but then it is getting crashed.
Below is the code which I have done.
-(IBAction) a
{
_picker = [[UIImagePickerController alloc] init];
_picker.sourceType = UIImagePickerControllerSourceTypeCamera;
_picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
_picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
_picker.showsCameraControls = YES;
_picker.navigationBarHidden =YES;
_picker.toolbarHidden = YES;
_picker.wantsFullScreenLayout = YES;
[_picker takePicture];
// Insert the overlay
OverlayViewController *overlay = [[OverlayViewController alloc] initWithNibName:#"OverlayViewController" bundle:nil];
overlay.pickerReference = _picker;
_picker.cameraOverlayView = overlay.view;
_picker.delegate = (id)self;
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(flashLight_On_Off) userInfo:nil repeats:YES];
[self presentModalViewController:_picker animated:NO];
}
- (void)flashLight_On_Off
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices)
{
if ([device hasFlash] == YES)
{
[device lockForConfiguration:nil];
if (bulPicker == FALSE)
{
[device setTorchMode:AVCaptureTorchModeOn];
bulPicker = TRUE;
}
else
{
[device setTorchMode:AVCaptureTorchModeOff];
bulPicker = FALSE;
}
[device unlockForConfiguration];
}
}
}
Is there any problem? Any other method to get the solution? I have to also stop blinking after taking image before pressing use button.
Please suggest me appropriate solution.
If I recall correctly the Cocoa naming convention, any method except - alloc, - copy and - mutableCopy returns an autoreleased object. In this case,
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
gets called 10 times a second, and each time it's autoreleased. It means that it may not be released immediately, so it will start eating up your RAM and the OS eventually detects this and kills the process of your app.
What you should do is wrap these kinds of operations into an autorelease pool if you know beforehand that they'll be called a lot.
- (void)toggleFlashlight
{
#autoreleasepool {
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices)
{
if ([device hasFlash]) {
[device lockForConfiguration:nil];
if (bulPicker) {
[device setTorchMode:AVCaptureTorchModeOff];
bulPicker = NO;
} else {
[device setTorchMode:AVCaptureTorchModeOn];
bulPicker = YES;
}
[device unlockForConfiguration];
}
}
}
}

Customised flashlight flashing?

Is there a way to let the flashlight of the iPhone flashing several times after clicking a button?
Like if I click a button the flashlight flashes only 3 times?
I havent found information about this on the web.
Could anyone help me with this?
And is there a way to make the flashes longer? like 2 seconds flash?
I dont know if someone of you dont understand what I mean: I want to turn on the flashlight for just 2 seconds and after 2 seconds it turns off itself.
My code is at the time:
- (void)loadView
{
[self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// If torch supported, add button to toggle flashlight on/off
if ([device hasTorch] == YES)
{
flashlightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 120, 320, 98)];
[flashlightButton setBackgroundImage:[UIImage imageNamed:#"TorchOn.png"] forState:UIControlStateNormal];
[flashlightButton addTarget:self action:#selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];
[[self view] addSubview:flashlightButton];
}
}
and to turn on and off:
- (void)buttonPressed:(UIButton *)button
{
if (button == flashlightButton)
{
if (flashlightOn == NO)
{
flashlightOn = YES;
[flashlightButton setBackgroundImage:[UIImage imageNamed:#"TorchOff.png"] forState:UIControlStateNormal];
}
else
{
flashlightOn = NO;
[flashlightButton setBackgroundImage:[UIImage imageNamed:#"TorchOn.png"] forState:UIControlStateNormal];
}
[self toggleFlashlight];
}
}
and for simulating taking picture:
- (void)toggleFlashlight
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device.torchMode == AVCaptureTorchModeOff)
{
// Create an AV session
AVCaptureSession *session = [[AVCaptureSession alloc] init];
// Create device input and add to current session
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
[session addInput:input];
// Create video output and add to current session
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
// Start session configuration
[session beginConfiguration];
[device lockForConfiguration:nil];
// Set torch to on
[device setTorchMode:AVCaptureTorchModeOn];
[device unlockForConfiguration];
[session commitConfiguration];
// Start the session
[session startRunning];
// Keep the session around
[self setAVSession:session];
[output release];
}
else
{
[AVSession stopRunning];
[AVSession release], AVSession = nil;
}
}
This should do the trick:
-(void)turnoff{
//YOUT TURN OFF CODE
}
-(void)doTurnOff{
[self performSelector:#selector(turnoff) withObject:nil afterDelay:2.0];
}
You can use NSTimer to create a sequence of on and off calls with any duration and interval gap that you need. The NSTimer callback can read the sequence of what to do next and when from an array or plist, etc. It's like building a timed sequential state machine.

How to use torch light in iPhone app?

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.
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
check this...
- (void)torchOnOff: (BOOL) onOff
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch]) {
[device lockForConfiguration:nil];
[device setTorchMode: onOff ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
[device unlockForConfiguration];
}
}

how to produce a light on shake gesture on iphone [duplicate]

I'm trying to make a flashlight app for my iPhone. I have an iPhone 4 and would like to utilize the LED on my iPhone for my project. Can anyone help me to get started with that?
Here is a shorter version you can now use to turn the LED on or off:
- (void)torchOnOff: (BOOL) onOff
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch]) {
[device lockForConfiguration:nil];
[device setTorchMode: onOff ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
[device unlockForConfiguration];
}
}
UPDATE: (March 2015)
You can also set the brightness of the torch:
- (void)setTorchToLevel:(float)torchLevel
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch]) {
[device lockForConfiguration:nil];
if (torchLevel <= 0.0) {
[device setTorchMode:AVCaptureTorchModeOff];
}
else {
if (torchLevel >= 1.0)
torchLevel = AVCaptureMaxAvailableTorchLevel;
BOOL success = [device setTorchModeOnWithLevel:torchLevel error:nil];
}
[device unlockForConfiguration];
}
}
Use the following:
AVCaptureSession * session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
[device unlockForConfiguration];
AVCaptureDeviceInput * flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
if (flashInput){
[session addInput:flashInput];
}
AVCaptureVideoDataOutput * output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
[output release];
[session commitConfiguration];
[session startRunning];
}
[self setTorchSession:session];
[session release];
(From a discussion on iPhoneDevSDK)

how can I make the torch/flash-on reliable when coming from multitask

When I leave the app and come back to it's 'on' sate sometimes it works fine by turning the torch/flash on but most of the time it either flashes or remains off.
AppDeligate.m
- (id) init {
torchState = TRUE;
if( (self=[super init] )) {
/// initialize flashlight
// test if this class even exists to ensure flashlight is turned on ONLY for iOS 4 and above
Class captureDeviceClass = NSClassFromString(#"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
if (device.torchMode == AVCaptureTorchModeOff) {
NSLog(#"Setting up flashlight for later use...");
AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
[device lockForConfiguration:nil];
[session addInput:flashInput];
[session addOutput:output];
[device unlockForConfiguration];
[output release];
[session commitConfiguration];
[session startRunning];
[self setTorchSession:session];
[session release];
}
}
}
}
return self;
}
- (void)toggleTorch {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[device lockForConfiguration:nil];
// For the first 4 to 5 times comming back from multiask this first if hits and works properly
if (torchState == TRUE && device.torchMode == AVCaptureTorchModeOff) {
NSLog(#"AVCaptureTorchModeOff setting On");
// On the 4th or 5th time it flashes and stays off or does nothing staying OFF
// even though the NSLog fires
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
} else if (torchState == TRUE && device.torchMode == AVCaptureTorchModeOn) {
// Sometimes this randomly fires and every time ErrorNotification fires too
NSLog(#"AVCaptureTorchModeOn");
if (AVCaptureSessionRuntimeErrorNotification) {
NSLog(#"ERROR");
// Try to force but doesn't do anything
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
}
} else {
NSLog(#"ALL IS OFF");
// when torch is in the off state it returns off as it should
torchState = FALSE;
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
}
[device unlockForConfiguration];
}
-(void) applicationDidEnterForeground:(UIApplication*)application {
[self toggleTorch];
}
The only thing I haven't included in code is a touch even that calls toggleTorch for on/off. That piece works great so again, what I'm testing here is turning it on at launch aka DidEnterForeground as well as when the app is returned to from a multitask session.
I would change 2 things:
1. add it to ApplicationDidBecomeActive
2. don't use toggle torch but set the state you want it to be (so you won't turn it off twice or on twice...). So change the function to toggleTorchWithState...
That what I've done in one of my apps and that works perfectly.