user1792444
user1792444

Reputation: 75

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

Upvotes: 7

Views: 6801

Answers (2)

user2350321
user2350321

Reputation: 1

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.

Upvotes: 0

Daniel Amitay
Daniel Amitay

Reputation: 6667

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

Upvotes: 13

Related Questions