Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dimming the LED for iPhone 5 flashlight app in Xcode

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];
        }
    }
}
like image 361
user1792444 Avatar asked Nov 01 '12 20:11

user1792444


1 Answers

- (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];
}
like image 193
Daniel Amitay Avatar answered Nov 07 '22 00:11

Daniel Amitay